名稱空間
變體
操作

std::add_pointer

來自 cppreference.com
< cpp‎ | 型別
 
 
超程式設計庫
型別特性
型別類別
(C++11)
(C++11)(DR*)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11) 
(C++11)
(C++11)
型別屬性
(C++11)
(C++11)
(C++14)
(C++11)(C++26 中已棄用)
(C++11)(直到 C++20*)
(C++11)(C++20 中已棄用)
(C++11)
型別特性常量
元函式
(C++17)
支援的操作
關係與屬性查詢
型別修改
(C++11)(C++11)(C++11)
型別轉換
(C++11)(C++23 中已棄用)
(C++11)(C++23 中已棄用)
(C++11)
(C++11)(直到 C++20*)(C++17)

(C++11)
(C++17)
編譯時有理數算術
編譯時整數序列
 
定義於標頭檔案 <type_traits>
template< class T >
struct add_pointer;
(C++11 起)

如果 T 是一個可引用型別或(可能 cv 限定的)void,則提供的成員 typedef typetypename std::remove_reference<T>::type*

否則,提供的成員 typedef typeT

如果程式為 std::add_pointer 新增特化,則行為是未定義的。

目錄

[編輯] 巢狀型別

名稱 定義
型別 如上確定

[編輯] 輔助型別

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++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 2101 C++11 如果 T 是帶有 cvref函式型別,則程式是病態的。 在這種情況下,生成的型別是 T

[編輯] 另見

檢查型別是否為指標型別
(類模板) [編輯]
從給定型別中移除指標
(類模板) [編輯]