std::add_cv, std::add_const, std::add_volatile
来自 cppreference.cn
定义于头文件 <type_traits> |
||
template< class T > struct add_cv; |
(1) | (since C++11) |
template< class T > struct add_const; |
(2) | (since C++11) |
template< class T > struct add_volatile; |
(3) | (since C++11) |
提供成员 typedef type
,它与 T
相同,但添加了 cv 限定符(除非 T
是函数、引用或已具有此 cv 限定符)
1) 同时添加 const 和 volatile
2) 添加 const
3) 添加 volatile
如果程序为此页面上描述的任何模板添加特化,则行为未定义。
目录 |
[edit] 成员类型
名称 | 定义 |
type
|
具有 cv 限定符的类型 T |
[edit] 辅助类型
template< class T > using add_cv_t = typename add_cv<T>::type; |
(since C++14) | |
template< class T > using add_const_t = typename add_const<T>::type; |
(since C++14) | |
template< class T > using add_volatile_t = typename add_volatile<T>::type; |
(since C++14) | |
[edit] 可能的实现
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; }; |
[edit] 注解
这些转换特性可以用于在模板实参推导中建立非推导语境
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>
[edit] 示例
运行此代码
#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
[edit] 参见
(C++11) |
检查类型是否为 const 限定 (类模板) |
(C++11) |
检查类型是否为 volatile 限定 (类模板) |
(C++11)(C++11)(C++11) |
从给定类型移除 const 和/或 volatile 说明符 (类模板) |
(C++17) |
获取对其参数的 const 引用 (函数模板) |