定义于头文件
<type_traits>
|
||
template< class T >
struct add_pointer; |
(C++11 起) | |
若 T
为引用类型,则提供成员 typedef type
,其为指向被引用类型的指针。
否则,若 T 指名对象类型、无 cv 或引用限定的 (C++17 起)函数类型或(可有 cv 限定的) void 类型,则提供成员 typedef type
,其为类型 T*
。
否则(若 T 为 cv 或引用限定的函数类型),提供成员 typedef |
(C++17 起) |
目录 |
名称 | 定义 |
type
|
指向 T 或 T 所引用类型的指针
|
template< class T >
using add_pointer_t = typename add_pointer<T>::type; |
(C++14 起) | |
namespace detail { template< class T, bool is_function_type = false > struct add_pointer { using type = typename std::remove_reference<T>::type*; }; template< class T > struct add_pointer<T, true> { using type = T; }; template< class T, class... Args > struct add_pointer<T(Args...), true> { using type = T(*)(Args...); }; template< class T, class... Args > struct add_pointer<T(Args..., ...), true> { using type = T(*)(Args..., ...); }; } // namespace detail template< class T > struct add_pointer : detail::add_pointer<T, std::is_function<T>::value> {}; |
#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++11)
|
检查类型是否为指针类型 (类模板) |
(C++11)
|
移除类型的指针修饰符 (类模板) |