定义于头文件
<type_traits>
|
||
template< class T >
struct remove_cv; |
(1) | (C++11 起) |
template< class T >
struct remove_const; |
(2) | (C++11 起) |
template< class T >
struct remove_volatile; |
(3) | (C++11 起) |
提供与 T
相同的成员 typedef type
,除了其最顶层 cv 限定符被移除。
1) 移除最顶层 const 、最顶层 volatile 或两者,若存在。
2) 移除最顶层 const
3) 移除最顶层 volatile
目录 |
名称 | 定义 |
type
|
无 cv 限定符的 T
|
template< class T >
using remove_cv_t = typename remove_cv<T>::type; |
(C++14 起) | |
template< class T >
using remove_const_t = typename remove_const<T>::type; |
(C++14 起) | |
template< class T >
using remove_volatile_t = typename remove_volatile<T>::type; |
(C++14 起) | |
template< class T > struct remove_cv { typedef typename std::remove_volatile<typename std::remove_const<T>::type>::type type; }; template< class T > struct remove_const { typedef T type; }; template< class T > struct remove_const<const T> { typedef T type; }; template< class T > struct remove_volatile { typedef T type; }; template< class T > struct remove_volatile<volatile T> { typedef T type; }; |
从 const volatile int * 移除 const/volatile 不修改该类型,因为该指针自身既非 const 亦非 volatile 。
#include <iostream> #include <type_traits> int main() { typedef std::remove_cv<const int>::type type1; typedef std::remove_cv<volatile int>::type type2; typedef std::remove_cv<const volatile int>::type type3; typedef std::remove_cv<const volatile int*>::type type4; typedef std::remove_cv<int * const volatile>::type type5; std::cout << "test1 " << (std::is_same<int, type1>::value ? "passed" : "failed") << '\n'; std::cout << "test2 " << (std::is_same<int, type2>::value ? "passed" : "failed") << '\n'; std::cout << "test3 " << (std::is_same<int, type3>::value ? "passed" : "failed") << '\n'; std::cout << "test4 " << (std::is_same<const volatile int*, type4>::value ? "passed" : "failed") << '\n'; std::cout << "test5 " << (std::is_same<int*, type5>::value ? "passed" : "failed") << '\n'; }
输出:
test1 passed test2 passed test3 passed test4 passed test5 passed
(C++11)
|
检查类型是否为 const 限定 (类模板) |
(C++11)
|
检查类型是否为 volatile 限定 (类模板) |
(C++11)
(C++11) (C++11) |
添加 const 或/与 volatile 限定符到给定类型 (类模板) |
(C++20)
|
将 std::remove_cv 与 std::remove_reference 结合 (类模板) |