std::add_pointer
提供: cppreference.com
<tbody>
</tbody>
| ヘッダ <type_traits> で定義
|
||
template< class T > struct add_pointer; |
(C++11以上) | |
T が参照型であれば、その参照先の型のポインタであるメンバ型 type が提供されます。
そうでなく、 T がオブジェクト型、 cv 修飾も参照修飾もされていない関数型、 void 型または cv 修飾された void 型であれば、型 T* であるメンバ型 type が提供されます。
そうでなければ (T が cv 修飾または ref 修飾された関数型の場合)、型 T であるメンバ型 type が提供されます。
メンバ型
| 名前 | 定義 |
type
|
T へのポインタ、または T の参照先の型へのポインタ
|
ヘルパー型
<tbody> </tbody> template< class T > using add_pointer_t = typename add_pointer<T>::type; |
(C++14以上) | |
実装例
namespace detail {
template <class T>
struct type_identity { using type = T; }; // または std::type_identity (C++20以上) を使用します。
template <class T>
auto try_add_pointer(int) -> type_identity<typename std::remove_reference<T>::type*>;
template <class T>
auto try_add_pointer(...) -> type_identity<T>;
} // namespace detail
template <class T>
struct add_pointer : decltype(detail::try_add_pointer<T>(0)) {};
|
例
Run this code
#include <iostream>
#include <type_traits>
int main()
{
int i = 123;
int& ri = i;
typedef std::add_pointer<decltype(i)>::type IntPtr;
typedef std::add_pointer<decltype(ri)>::type IntPtr2;
IntPtr pi = &i;
std::cout << "i = " << i << "\n";
std::cout << "*pi = " << *pi << "\n";
static_assert(std::is_pointer<IntPtr>::value, "IntPtr should be a pointer");
static_assert(std::is_same<IntPtr, int*>::value, "IntPtr should be a pointer to int");
static_assert(std::is_same<IntPtr2, IntPtr>::value, "IntPtr2 should be equal to IntPtr");
typedef std::remove_pointer<IntPtr>::type IntAgain;
IntAgain j = i;
std::cout << "j = " << j << "\n";
static_assert(!std::is_pointer<IntAgain>::value, "IntAgain should not be a pointer");
static_assert(std::is_same<IntAgain, int>::value, "IntAgain should be equal to int");
}
出力:
i = 123
*pi = 123
j = 123
欠陥報告
以下の動作変更欠陥報告は以前に発行された C++ 標準に遡って適用されました。
| DR | 適用先 | 発行時の動作 | 正しい動作 |
|---|---|---|---|
| LWG 2101 | C++11 | std::add_pointer was required to producepointer to cv-/ref-qualified function types. |
Produces cv-/ref-qualified function types themselves. |
関連項目
(C++11) |
型がポインタ型かどうか調べます (クラステンプレート) |
(C++11) |
指定された型からポインタを削除します (クラステンプレート) |