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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With