1

谁能告诉我为什么通用引用会失去顶级简历的资格?我预计输出将在以下代码中的第二个和第三个函数调用中为 const 返回 true。

#include <iostream>
#include <type_traits>

using namespace std;

template<class T>
void print(T const &value){
    cout << "Printing from const & method: " << value << endl;
}

template<class T>
void print(T const *value){
    cout << "Printing from const * method: " << *value << endl;
}

template<class T>
void f(T&& item){
    cout << "T is const: " << boolalpha << is_const<decltype(item)>::value << endl;

    print(std::forward<T>(item));
}


int main(){

    f(5);

    const int a = 5;
    f(a);

    const int * const ptr = &a;

    f(ptr);

    return 0;
}

输出:

T is const: false
Printing from const & method: 5
T is const: false
Printing from const & method: 5
T is const: false
Printing from const * method: 5
4

1 回答 1

4

正如 R. Martinho 指出的那样,引用没有顶级 const。

要检查较低级别的 const-ness,您可以使用std::remove_reference

cout << "T is const: " << boolalpha
     << is_const<typename remove_reference<decltype(item)>::type>::value
     << endl;
于 2013-07-04T14:31:20.107 回答