0

How can I get the type of an expression including references? So that the following pseudocode will give different results all 3 times.

int a = 5;
std::cout << type(a) << std::endl;
int &b = a;
std::cout << type(b) << std::endl;
int &&c = 5;
std::cout << type(c) << std::endl;

(typeid ignores references for some reason so it's not an option.)

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
ledonter
  • 1,269
  • 9
  • 27
  • For which purpose? – Holt Jul 18 '17 at 19:14
  • 3
    What is the *actual* problem you want to solve? Why do you need the type with references? Please read about [the XY problem](http://xyproblem.info/) and think about how your question might be one. – Some programmer dude Jul 18 '17 at 19:14
  • @Someprogrammerdude I'me just learning the language and trying to figure out exact expression types :) Do you imply it's never practically needed to distinguish those? – ledonter Jul 18 '17 at 19:16
  • @ledonter There is, but not at runtime like you are trying to achieve. The best you can have (without relying on some sort of compiler specific extension), is `typeid`. – Rakete1111 Jul 18 '17 at 19:17
  • @Rakete1111 maybe some implementation-specific intrinsics/flags? – ledonter Jul 18 '17 at 19:18
  • @ledonter I don't know any, but some answers here might help you :) – Rakete1111 Jul 18 '17 at 19:21
  • Most cases when a type is used to select different cases at run-time it's due to bad design. The use-cases when it's truly needed are very few and far far apart, and will typically only be needed for a very special cases when the programmer implementing it should be experienced enough to be able to work around it. – Some programmer dude Jul 18 '17 at 19:24
  • https://stackoverflow.com/a/20170989/4672588 – cpplearner Jul 19 '17 at 04:23

1 Answers1

3

If you just need to see a deduced type, one trick is to make a template that fails to instantiate:

template<typename T> struct TD;
TD<decltype(a)> tda;
TD<decltype(b)> tdb;
TD<decltype(c)> tdc;

This will cause compile errors that tell you the type of a/b/c.

0x5453
  • 12,753
  • 1
  • 32
  • 61