C ++ 11: persistence in perfect forwarding

I created a function to determine the constant and l (r) value of the argument.

template<class T> std::string
detect(typename std::remove_reference<T>::type&&) {
    return std::string(std::is_const<T>::value ? "const " : "") + "rvalue";
}
template<class T> std::string
detect(typename std::remove_reference<T>::type&) {
    return std::string(std::is_const<T>::value ? "const " : "") + "lvalue";
}

for some reason, is_const always returns false even in const types, for example const int &. I tried to add another overload to fix the constant

template<class T> std::string
detect(const typename std::remove_reference<T>::type& ) { return "const lvalue"; }

the compiler then complains that the detection is ambiguous when applied to const int &. Therefore, I think the compiler has the correct value T = const int &, but why is_const does not return true?

+3
source share
1 answer

std::is_const<T>detects only the upper level const. For example foo constor foo* const. He does not care about "internal" consts, such as foo const*or foo const&.

, const, , const :

std::is_const<typename std::remove_reference<T>::type>::value

, T, detect<foo const&>(x). , - ?

template<class T> std::string
detect(T&&) { // have T be deduced
    return std::string(std::is_const<typename std::remove_reference<T>::type>::value ? "const " : "")
         + (std::is_lvalue_reference<T>::value? "lvalue" : "rvalue");
}

detect(x).

+9

All Articles