Normally, if I need to detect whether a type is const I just use boost::is_const. However, I ran into trouble when trying to detect the const-ness of a nested type. Consider the following traits template, which is specialized for const types:
template <class T>
struct traits
{
typedef T& reference;
};
template <class T>
struct traits<const T>
{
typedef T const& reference;
};
The problem is that boost::is_const doesn’t seem to detect that traits<const T>::reference is a const type.
For example:
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;
This outputs: false false
Why doesn’t it output false true?
Because the reference is not const, it’s the type it’s referencing that is const. Right, there are no const references. So imagine that the reference is a pointer, then the difference is easier to understand:
int const*not const,int *constis const.Use remove_reference to get the actual const type: