通常,如果我需要检测一个类型是否是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>::reference
是 const
类型。
例如:
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/