c++ - 检测嵌套类型的常量性

标签 c++ templates constants traits

通常,如果我需要检测一个类型是否是const我只是用 boost::is_const .但是,我在尝试检测嵌套类型的常量性时遇到了麻烦。考虑以下专用于 const 类型的特征模板:

template <class T>
struct traits
{
    typedef T& reference;
};

template <class T>
struct traits<const T>
{
    typedef T const& reference;
};

问题是 boost::is_const似乎没有检测到 traits<const T>::referenceconst类型。

例如:

std::cout << std::boolalpha;
std::cout << boost::is_const<traits<int>::reference>::value << " ";
std::cout << boost::is_const<traits<const int>::reference>::value << std::endl;

输出:false false

为什么不输出false true

最佳答案

因为引用不是常量,所以它引用的类型是常量。对,没有 const 引用。所以把引用想象成一个指针,那么区别就更容易理解了:int const*不是const,int *const是const。

使用 remove_reference 获取实际的常量类型:

cout << boost::is_const<
            boost::remove_reference<int const&>::type>::value << '\n';

关于c++ - 检测嵌套类型的常量性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4683840/

相关文章:

c++ - 从 ActiveX 控件中的方法返回值

C++ 字符串两边的括号

c++ - 我可以告诉我的类是从哪个模板实例类继承的吗?

c++ - 使用常量设置变量类型

c++ - 轮廓区域未显示所有相关区域

c# - 通过导出 dll 从 CUDA 中的指针加载图像

c++ - 导致过载解析头痛的原因是什么?

c++ - VectorList 类构造函数

c# - 为什么不能声明类型为 System.Drawing.Color 的常量?

c - 如何保留仅包含 const 值的变量指针