获取模板类型的基类型(移除const/reference等)
Get base type of a template type (remove const/reference/etc.)
是否存在返回给定类型的基类型的类型特征模板?我所说的基类型是指去掉了所有值修饰符、const、volatile等的类型。例如,使用假设的特征函数:
base<int>::type == int
base<int const>::type == int
base<int&>::type == int
我知道remove_const
和remove_reference
,目前只是将它们组合使用。我想知道是否已经存在这样一种特质,也许我所指的东西有一个合适的名字?
我可能会定义一个类型别名,如:
template<typename T>
using base_type = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
请注意,在一篇不再可用的文章中,R. Martinho Fernandes提出将这种类型别名命名为Unqualified
。
另一方面,标准类型特征std::decay
与上面的和对数组和函数类型做了相同的操作,这可能是您想要的,也可能不是。
尝试std::decay
。它模仿按值传递参数给函数时发生的情况:剥离顶级cv限定符、引用,将数组转换为指针,将函数转换为函数指针。
问候,div, rzej
显然,这取决于您想要从类型中删除什么。std::decay可能是您正在寻找的(删除引用,const/volatile
,将数组衰变为指针和函数衰变为函数指针)。如果您不希望数组指针和函数指针衰减,则需要坚持使用std::remove_reference
和std::remove_cv
(删除const
和volatile
)。当然,你可以把这两个组合到你自己的typetrait中,使它更容易使用。
c++ 20给出了std::remove_cvref_t
用于此目的。
以前,你可以做std::remove_cv_t<std::remove_reference_t<T>>
。
还有std::decay_t
,但它额外将数组/函数转换为指针等
相关文章:
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 视觉工作室 2017;启用 /permissive 时,类型 "const wchar_t *" 的参数与类型 "PWSTR" 的参数不兼容
- 无法使用类型 'const char *' 的左值初始化类型 'char *' 的成员子对象
- "const wchar_t *" 类型的值不能用于初始化类型 "const PWSTR" 的实体
- 错误:对类型 'const ItemInstance' 的引用无法绑定到类型 'void' 的右值
- C++ 类型 "char" 的参数与类型 "const char" 的参数不兼容
- 在这种情况下,如何从类型 "const char*" 初始化字段?
- 类型"const char[2]"的值不能隐式转换为"int"错误C++
- 错误:数组下标的类型"const bool[int]"无效
- 错误:C2679 二进制"==":未找到采用类型 'const std::string' 的右侧操作数的运算符(或者没有可接受的转换)
- 类型 "const char *" 的参数与类型 "char *" 的参数不兼容
- 错误:"->"的基本操作数具有非指针类型"const"
- 作为返回类型"const int&"做什么?
- 类型 "const char*" 的参数与类型 "char*" 的参数不兼容。但是为什么?:(
- 类型 "const char*" 的参数与类型 "Person" 的参数不兼容
- C++:"错误:类型'const char*'和'const char [28]'的操作数无效到二进制'ope
- 类型 "const char *" 的参数与类型 "LPCWSTR" 的参数不兼容
- 错误:从不兼容的类型 'const char *' 分配给'char'
- 类型 "const char *" 的默认参数与类型 "char *" 的参数不兼容
- 类型 "const char *" 的参数与 "LPSTR" C++ 类型的参数不兼容