Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Methods of store type_info objects doesn't work

I'm having some trouble understanding the correspondance between the return type of typeid and actual type_info objects which seems to work differently from usual objects. For example, I can do...

std::cout << typeid(int).name() << std::endl;

...and get a decent behaviour form the program... but this won't compile...

std::type_info a(int);
std::cout << a.name() << std::endl; 

Compiler outputs:

type_info.cpp: In function 'int main()':
type_info.cpp:6:17: error: request for member 'name' in 'a', which is of non-class type 'std::type_info(int)'

...nor can I do...

if(a == typeid(int)) {/*Do something*/ } //Looong error message

What am I missing?

like image 630
fast-reflexes Avatar asked Oct 10 '14 13:10

fast-reflexes


1 Answers

First off, vexing parse:

std::type_info a(int);

a is a function (taking int and returning std::type_info).

Second, std::type_info is not copyable, so you cannot store it by value. You can use a reference if it suits your needs:

const std::type_info &a(typeid(int));

If you need to actually store std::type_info objects (as if) "by value," use std::type_index instead; it was designed for this:

std::type_index a(typeid(int));
std::cout << a.name() << std::endl;
like image 115
Angew is no longer proud of SO Avatar answered Sep 21 '22 00:09

Angew is no longer proud of SO