名稱空間
變體
操作

std::add_cv, std::add_const, std::add_volatile

來自 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)
支援的操作
關係與屬性查詢
型別修改
add_cvadd_constadd_volatile
(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_cv;
(1) (C++11 起)
template< class T >
struct add_const;
(2) (C++11 起)
template< class T >
struct add_volatile;
(3) (C++11 起)

提供成員 typedef type,其與 T 相同,但添加了 cv 限定符(除非 T 是函式、引用或已具有此 cv 限定符)

1) 新增 constvolatile
2) 新增 const
3) 新增 volatile

如果程式為此頁上描述的任何模板新增特化,則行為未定義。

目錄

[編輯] 成員型別

名稱 定義
型別 帶有 cv 限定符的型別 T

[編輯] 輔助型別

template< class T >
using add_cv_t       = typename add_cv<T>::type;
(C++14 起)
template< class T >
using add_const_t    = typename add_const<T>::type;
(C++14 起)
template< class T >
using add_volatile_t = typename add_volatile<T>::type;
(C++14 起)

[編輯] 可能的實現

template<class T> struct add_cv { typedef const volatile T type; };
 
template<class T> struct add_const { typedef const T type; };
 
template<class T> struct add_volatile { typedef volatile T type; };

[編輯] 備註

這些轉換特性可用於在模板引數推導中建立非推導上下文

template<class T>
void f(const T&, const T&);
 
template<class T>
void g(const T&, std::add_const_t<T>&);
 
f(4.2, 0); // error, deduced conflicting types for 'T'
g(4.2, 0); // OK, calls g<double>

[編輯] 示例

#include <iostream>
#include <type_traits>
 
struct foo
{
    void m() { std::cout << "Non-cv\n"; }
    void m() const { std::cout << "Const\n"; }
    void m() volatile { std::cout << "Volatile\n"; }
    void m() const volatile { std::cout << "Const-volatile\n"; }
};
 
int main()
{
    foo{}.m();
    std::add_const<foo>::type{}.m();
    std::add_volatile<foo>::type{}.m();
    std::add_cv<foo>::type{}.m();
}

輸出

Non-cv
Const
Volatile
Const-volatile

[編輯] 另請參閱

(C++11)
檢查型別是否為 const 限定
(類模板) [編輯]
檢查型別是否為 volatile 限定
(類模板) [編輯]
從給定型別中移除 const 和/或 volatile 限定符
(類模板) [編輯]
(C++17)
獲取其引數的 const 引用
(函式模板) [編輯]