通用引用忽略顶级cv限定符

时间:2013-07-04 14:12:04

标签: c++ templates c++11 universal-reference

有谁可以告诉我为什么通用引用松散顶级cv资格?我希望在下面的代码中,第二次和第三次函数调用的输出将为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

1 个答案:

答案 0 :(得分:4)

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

要检查较低级别的常量,可以使用std::remove_reference

cout << "T is const: " << boolalpha
     << is_const<typename remove_reference<decltype(item)>::type>::value
     << endl;