3

我创建了函数来检测参数的 constness 和 l(r)valueness。

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";
}

出于某种原因,即使在 const 类型(例如 const int&)上,is_const 也总是返回 false。我尝试添加另一个重载来捕获常量

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

然后编译器抱怨当应用于 const int& 时检测不明确。所以我认为编译器已经正确计算出 T=const int&,但为什么 is_const 不返回 true?

4

1 回答 1

10

std::is_const<T>仅检测顶级const. 像foo const,或foo* const。它不关心“内部” const,比如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)

于 2012-04-26T18:00:09.890 回答