remove_cv
去掉变量的cv属性,获取其原始类型信息。
实现方式
模版推导丢弃const和volatile参数。
性能开销
模版推导完成操作,不涉及运行时开销。
调用stl
remove_const
remove_volatile
// Const-volatile modifications.
/// remove_const
template<typename _Tp>
struct remove_const
{ typedef _Tp type; };
template<typename _Tp>
struct remove_const<_Tp const>
{ typedef _Tp type; };
/// remove_volatile
template<typename _Tp>
struct remove_volatile
{ typedef _Tp type; };
template<typename _Tp>
struct remove_volatile<_Tp volatile>
{ typedef _Tp type; };
/// remove_cv
template<typename _Tp>
struct remove_cv
{
typedef typename
remove_const<typename remove_volatile<_Tp>::type>::type type;
};
代码示例
代码源地址:http://www.cplusplus.com/reference/type_traits/remove_cv/
自己添加了b、c、const char*的输出。
这里b、c都会被去掉const,这是模版自动完成的吗?有些小疑问?
// remove_cv example
#include <iostream>
#include <type_traits>
int main() {
typedef const volatile char cvchar;
std::remove_cv<cvchar>::type a; // char a
std::remove_cv<char* const>::type b; // char* b
std::remove_cv<const char*>::type c; // const char* c (no changes)
if (std::is_const<decltype(a)>::value)
std::cout << "type of a is const" << std::endl;
else
std::cout << "type of a is not const" << std::endl;
if (std::is_volatile<decltype(a)>::value)
std::cout << "type of a is volatile" << std::endl;
else
std::cout << "type of a is not volatile" << std::endl;
if (std::is_const<decltype(b)>::value)
std::cout << "type of b is const" << std::endl;
else
std::cout << "type of b is not const" << std::endl;
if (std::is_const<decltype(c)>::value)
std::cout << "type of c is const" << std::endl;
else
std::cout << "type of c is not const" << std::endl;
if (std::is_const<const char*>::value)
std::cout << "type of const char* is const" << std::endl;
else
std::cout << "type of const char* is not const" << std::endl;
return 0;
}
Output:
type of a is not const
type of a is not volatile
type of b is not const
type of c is not const
type of const char* is not const
应用场景
Obtains the type T without any top-level const or volatile qualification.
参考:gcc8源码