命名空间
变体
操作

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

来自 cppreference.cn
< 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 引用
(函数模板) [编辑]