Cha*_*l72 8 c++ templates const traits
通常情况下,如果我需要检测一种类型是否const只是使用boost::is_const.但是,在尝试检测嵌套类型的常量时遇到了麻烦.考虑以下traits模板,它专门用于const类型:
template <class T>
struct traits
{
typedef T& reference;
};
template <class T>
struct traits<const T>
{
typedef T const& reference;
};
Run Code Online (Sandbox Code Playgroud)
问题是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;
Run Code Online (Sandbox Code Playgroud)
这输出: false false
为什么不输出false true?
ybu*_*ill 13
因为引用不是const,所以它引用的类型是const.没错,没有const引用.所以假设引用是一个指针,那么差异更容易理解:int const*不是const,int *const是const.
使用remove_reference来获取实际的const类型:
cout << boost::is_const<
boost::remove_reference<int const&>::type>::value << '\n';
Run Code Online (Sandbox Code Playgroud)
因为引用不是const.:)
你有一个ref-to-const(考虑一个粗略的模拟int const*,其中指针int有一个const上下文,但指针本身没有).标准混合了这里的术语,但我避免使用"const ref"这个词,这是一个很容易引起误解的词.
引用本质上是不可变的,因为它们只能初始化然后不能重新绑定,但这并不能使它们成为可能const.
您可以从类型中删除引用boost::remove_reference(如其他答案中所示).