26

Consider the code:

int const  x = 50;
int const& y = x;
cout << std::is_const<decltype(x)>::value << endl; // 1
cout << std::is_const<decltype(y)>::value << endl; // 0

This makes sense, because y is not a const reference, it is a reference to a const.

Is there a foo such that std::foo<decltype(y)>::value is 1? If not, what would it look like to define my own?

Praetorian
  • 106,671
  • 19
  • 240
  • 328
Claudiu
  • 224,032
  • 165
  • 485
  • 680

1 Answers1

24

Use remove_reference:

#include <string>
#include <iostream>
#include <type_traits>
using namespace std;

int main()
{
    int const  x = 50;
    int const& y = x;
    cout << std::is_const<std::remove_reference<decltype(x)>::type>::value << endl; // 1
    cout << std::is_const<std::remove_reference<decltype(y)>::type>::value << endl; // 1

    return 0;
}

See on coliru

Borgleader
  • 15,826
  • 5
  • 46
  • 62
  • Why remove reference to a not reference integer? – Adam Jun 12 '15 at 15:37
  • @WhyCry To show that it works whether or not the underlying thing is a reference or not. I'm assuming OP was looking for a general solution. – Borgleader Jun 12 '15 at 15:38
  • `cout << std::is_const::value << endl;` // 1 `cout << std::is_const::type>::value << endl;` So these are essentially the same in a less general sense. (My conclusions) – Adam Jun 12 '15 at 15:40
  • 2
    remove_reference has no effect if T is not a reference, as stated in the documentation. – Borgleader Jun 12 '15 at 15:42
  • Would putting an even more generalized version be a valid answer to this question? – Adam Jun 12 '15 at 15:43
  • 1
    @WhyCry Here's something even easier: `cout << 1 << endl; cout << 1 << endl;` :) If you have the luxury of knowing types a priori then why bother with type traits at all? If you want a general solution that works when the type maybe `const`, or reference to `const`, then you need something like the code above. – Praetorian Jun 12 '15 at 15:43
  • I understand it now, I was just trying to apply it in a more general sense where instead of `decltype(variable)`, one could just add `int const` or `int const &`. I'm not arguing, just applying it within my own context in my editor` for my **own** understanding :). – Adam Jun 12 '15 at 15:46
  • @WhyCry Substituting decltype(x)/decltype(y) for the real types works too [as you can see](http://coliru.stacked-crooked.com/a/da97b64d421e5b1e) – Borgleader Jun 12 '15 at 15:48
  • I'm not saying it's not. I was simply stating how generically this can be applied! I'm complementing the power of the code of your answer, not pushing it down. – Adam Jun 12 '15 at 15:49