std::add_pointer

定义于头文件 <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 type ,其为类型 T

(C++17 起)

目录

成员类型

名称 定义
type 指向 TT 所引用类型的指针

帮助类型

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)
检查类型是否为指针类型
(类模板)
移除类型的指针修饰符
(类模板)

版本历史

  • (当前 | 先前 2017年7月23日 (日) 02:18Fruderica讨论 | 贡献. . (2,703字节) (+1,434). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 18:11P12bot讨论 | 贡献 . . (1,269字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 11:38P12bot讨论 | 贡献 . . (1,269字节) (-109). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 17:32P12bot讨论 | 贡献 . . (1,378字节) (+233). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月27日 (六) 11:35P12讨论 | 贡献 . . (1,145字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 06:00TranslationBot讨论 | 贡献. . (1,145字节) (-39). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 03:32P12讨论 | 贡献 . . (1,184字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (1,184字节) (+1,184). . (Translated from the English version using Google Translate)