std::add_pointer - cppreference.com
来自cppreference.com
template< class T > struct add_pointer; |
(C++11 起) | |
如果 T 是引用类型,那么提供的成员 typedef type 是指向被引用类型的指针。
否则,如果 T 指名的是一个对象类型,无 cv 或引用限定的函数类型,或者(可能 cv 限定的)void 类型,那么提供的成员 typedef type 是类型 T*。
否则(当 T 是 cv 或引用限定的函数类型),提供的成员 typedef type 为类型 T。
如果程序添加了 std::add_pointer 的特化,那么行为未定义。
成员类型
| 名字 | 定义 |
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>; // 特殊情况(不能组成 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 是一个“糟糕的函数类型” using FF = std::add_pointer_t<F>; static_assert(std::is_same_v<F, FF>, "FF 应该正好是 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 应该是指针"); static_assert(std::is_same_v<IntPtr, int*>, "IntPtr 应该是指向 int 的指针"); static_assert(std::is_same_v<IntPtr2, IntPtr>, "IntPtr2 应该等于 IntPtr"); typedef std::remove_pointer<IntPtr>::type IntAgain; IntAgain j = i; std::cout << "j = " << j << '\n'; static_assert(!std::is_pointer_v<IntAgain>, "IntAgain 不应该是指针"); static_assert(std::is_same_v<IntAgain, int>, "IntAgain 应该等于 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++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 2101 | C++11 | 规定 std::add_pointer 产生指向 cv/引用 限定函数类型的指针。 |
产生 cv/引用限定函数类型自身。
before=在 |