需要澄清.C++ type_traits

Clarification wanted re. C++ type_traits

本文关键字:type traits C++      更新时间:2023-10-16
似乎

要测试恒定性,必须测试模板参数,但要测试右值性,必须测试实际参数。(这是使用 VC++ 2012。这段代码说明了我的意思:

#include <type_traits>
#include <string>
#include <iostream>
using namespace std;
template<class T>
void f(T& x) {
    cout << "f() is_const<T> and is_const<decltype<x)>" << endl;
    cout << is_const<T>::value << endl; // Prints 1 when arg is const
    cout << is_const<decltype(x)>::value << endl; // Prints 0 when arg is const
}
template<class T>
void g(T&& x) {
    cout << "g() is_const<T> and is_const<decltype<x)>" << endl;
    cout << is_const<T>::value << endl; // Prints 0 when arg is const
    cout << is_const<decltype(x)>::value << endl; // Prints 0 when arg is cons
    cout << "g() is_rvalue_reference<T> and is_rvalue_reverence<decltype(x)>" <<endl;
    cout << is_rvalue_reference<T>::value << endl; // Prints 0 when arg is rvlaue
    cout << is_rvalue_reference<decltype(x)>::value << endl; // Prints 1 when arg is rvalue
}
int main()
{
    const std::string str;
    f(str); // const argument
    cout << endl;
    g(std::string("")); // rvalue argument
    return 0;
} 

我很难理解为什么会这样。有人可以解释,或者指出我解释它的文章吗?如果需要,我将深入研究C++11标准。有人知道相关部分吗?

原因是你误解了事情。 在任何这些示例中,x都不会const,仅仅是因为没有const引用类型(无论如何都无法更改引用的内容)。在is_const<T>中,您基本上忽略了您将x声明为T&

类似的误解也发生在右值参考测试中。T&&中的T(称为通用引用,顺便说一句)将在传递左值时推导出为U&,传递右值时推导出为U。在测试is_rvalue_reference<T>时,您再次忽略了您将x声明为T&&。在测试is_const<T>时,您没有考虑到T将成为参考的事实,如上所述,这永远无法const

g的正确测试是

  • std::is_const<typename std::remove_reference<T>::type>::value
  • std::is_rvalue_reference<T&&>::value