名前空間
変種
操作

std::add_pointer

提供: cppreference.com
< cpp‎ | types
 
 
ユーティリティライブラリ
汎用ユーティリティ
日付と時間
関数オブジェクト
書式化ライブラリ (C++20)
(C++11)
関係演算子 (C++20で非推奨)
整数比較関数
(C++20)
スワップと型操作
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
一般的な語彙の型
(C++11)
(C++17)
(C++17)
(C++17)
(C++17)

初等文字列変換
(C++17)
(C++17)
 
型サポート
型の性質
(C++11)
(C++11)
(C++14)
(C++11)
(C++11)(C++20未満)
(C++11)(C++20で非推奨)
(C++11)
型特性定数
メタ関数
(C++17)
定数評価文脈
サポートされている操作
関係と性質の問い合わせ
型変更
(C++11)(C++11)(C++11)
型変換
(C++11)
(C++11)
(C++17)
(C++11)(C++20未満)(C++17)
 
ヘッダ <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 の参照先の型へのポインタ

[編集] ヘルパー型

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)) {};

[編集]

#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 produce
pointer to cv-/ref-qualified function types.
Produces cv-/ref-qualified function types themselves.

[編集] 関連項目

型がポインタ型かどうか調べます
(クラステンプレート) [edit]
指定された型からポインタを削除します
(クラステンプレート) [edit]