1

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
Nate Kohl
  • 35,264
  • 10
  • 43
  • 55
Blair Davidson
  • 901
  • 12
  • 35

1 Answers1

4

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;
Nate Kohl
  • 35,264
  • 10
  • 43
  • 55