std::remove_cv, std::remove_const, std::remove_volatile
来自cppreference.com
<tbody>
</tbody>
| 在标头 <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
|
辅助类型
<tbody> </tbody> 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 T type; };
template<class T> struct remove_cv<const T> { typedef T type; };
template<class T> struct remove_cv<volatile T> { typedef T type; };
template<class T> struct remove_cv<const volatile T> { typedef T 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 <type_traits>
template<typename U, typename V>
constexpr bool same = std::is_same_v<U, V>;
static_assert
(
same<std::remove_cv_t<int>, int> &&
same<std::remove_cv_t<const int>, int> &&
same<std::remove_cv_t<volatile int>, int> &&
same<std::remove_cv_t<const volatile int>, int> &&
// remove_cv 仅对类型有效,而非指针
not same<std::remove_cv_t<const volatile int*>, int*> &&
same<std::remove_cv_t<const volatile int*>, const volatile int*> &&
same<std::remove_cv_t<const int* volatile>, const int*> &&
same<std::remove_cv_t<int* const volatile>, int*>
);
int main() {}
参阅
(C++11) |
检查类型是否为 const 限定 (类模板) |
(C++11) |
检查类型是否为 volatile 限定 (类模板) |
(C++11)(C++11)(C++11) |
向给定类型添加 const 和/或 volatile 限定符 (类模板) |
(C++20) |
将 std::remove_cv 与 std::remove_reference 结合 (类模板) |