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

定义于头文件 <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 起)

提供同 T 的成员 typedef type ,除了它拥有添加的 cv 限定符(除非 T 是函数、引用或已拥有 cv 限定符)

1) 添加 constvolatile

2) 添加 const

3) 添加 volatile

目录

成员类型

名称 定义
type 带 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; };

示例

#include <iostream>
#include <type_traits>
 
struct foo
{
    void m() { std::cout << "Non-cv\n"; }
    void m() const { std::cout << "Const\n"; }
};
 
template <class T>
void call_m()
{
    T().m();
}
 
int main()
{
    call_m<foo>();
    call_m<std::add_const<foo>::type>();
}

输出:

Non-cv
Const

参阅

(C++11)
检查类型是否为 const 限定
(类模板)
(C++11)
检查类型是否为 volatile 限定
(类模板)
从给定类型移除 const 或/与 volatile 限定符
(类模板)
(C++17)
获得到其参数的 const 引用
(函数模板)

版本历史

  • (当前 | 先前 2017年11月26日 (日) 09:46Fruderica讨论 | 贡献 . . (1,885字节) (0). . (撤销)
  • 当前 | 先前 2017年7月22日 (六) 23:44Fruderica讨论 | 贡献. . (1,885字节) (+392). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 18:11P12bot讨论 | 贡献 . . (1,493字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 11:37P12bot讨论 | 贡献 . . (1,493字节) (-176). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 17:34P12bot讨论 | 贡献 . . (1,669字节) (+193). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月27日 (六) 11:35P12讨论 | 贡献 . . (1,476字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 06:00TranslationBot讨论 | 贡献. . (1,476字节) (-30). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 03:32P12讨论 | 贡献 . . (1,506字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (1,506字节) (+1,506). . (Translated from the English version using Google Translate)