获取模板类型的基类型(移除const/reference等)

Get base type of a template type (remove const/reference/etc.)

本文关键字:类型 const reference 移除 基类 获取      更新时间:2023-10-16

是否存在返回给定类型的基类型的类型特征模板?我所说的基类型是指去掉了所有值修饰符、const、volatile等的类型。例如,使用假设的特征函数:

base<int>::type == int
base<int const>::type == int
base<int&>::type == int

我知道remove_constremove_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_referencestd::remove_cv(删除constvolatile)。当然,你可以把这两个组合到你自己的typetrait中,使它更容易使用。

c++ 20给出了std::remove_cvref_t用于此目的。

以前,你可以做std::remove_cv_t<std::remove_reference_t<T>>

还有std::decay_t,但它额外将数组/函数转换为指针等

相关文章: