std::add_pointer
From cppreference.com
| ヘッダ <type_traits> で定義 |
||
| template< class T > struct add_pointer; |
(C++11以降) | |
T が 参照可能な型 または(cv修飾されている可能性のある)void の場合、メンバ型エイリアス type は typename std::remove_reference<T>::type* です。
それ以外の場合、メンバ型エイリアス type は T です。
プログラムが std::add_pointer の特殊化を追加した場合、動作は未定義です。
目次 |
[編集] ネストされた型
| 名前 | 定義 |
type
|
上記のように決定されます |
[編集] ヘルパー型
| 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; }; // or use std::type_identity (since C++20) template<class T> auto try_add_pointer(int) -> type_identity<typename std::remove_reference<T>::type*>; // usual case template<class T> auto try_add_pointer(...) -> type_identity<T>; // unusual case (cannot form std::remove_reference<T>::type*) } // namespace detail template<class T> struct add_pointer : decltype(detail::try_add_pointer<T>(0)) {}; |
[編集] 例
このコードを実行
#include <iostream> #include <type_traits> template<typename F, typename Class> void ptr_to_member_func_cvref_test(F Class::*) { // F is an “abominable function type” using FF = std::add_pointer_t<F>; static_assert(std::is_same_v<F, FF>, "FF should be precisely F"); } struct S { void f_ref() & {} void f_const() const {} }; 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_v<IntPtr>, "IntPtr should be a pointer"); static_assert(std::is_same_v<IntPtr, int*>, "IntPtr should be a pointer to int"); static_assert(std::is_same_v<IntPtr2, IntPtr>, "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_v<IntAgain>, "IntAgain should not be a pointer"); static_assert(std::is_same_v<IntAgain, int>, "IntAgain should be equal to int"); ptr_to_member_func_cvref_test(&S::f_ref); ptr_to_member_func_cvref_test(&S::f_const); }
出力
i = 123 *pi = 123 j = 123
[編集] 不具合報告
以下の動作変更を伴う欠陥報告が、以前に公開されたC++標準に遡って適用されました。
| DR | 適用対象 | 公開された動作 | 正しい動作 |
|---|---|---|---|
| LWG 2101 | C++11 | T が cv または ref を持つ 関数型 である場合、プログラムは不正な形式でした。 |
この場合、生成される型は T です。 |
[編集] 関連項目
| (C++11) |
型がポインタ型であるかをチェックする (クラステンプレート) |
| (C++11) |
与えられた型からポインタを削除する (クラステンプレート) |