Search code examples
c++templatesc++11universal-reference

universal reference ignores top level cv qualifier


Can anyone tell me why univeral references loose the top-level cv qualifies? I expected the output would return true for const on the second and third function calls in the following code.

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

Output:

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

Solution

  • As R. Martinho pointed out, references don't have top-level const.

    To check lower-level const-ness, you can use std::remove_reference:

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