Reputation: 5176
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?
Upvotes: 7
Views: 6452
Reputation: 7486
std::type_info
is neither copy-constructible nor copy-assignable. Thus you can't do stuff like std::type_info a = typeid(...)
.
const std::type_info &someTypeId(typeid(someType));
You can also store a pointer to a std::type_info
object, because typeid returns a lvalue.
There is also std::type_index
in case you want to use std::type_info
objects as a key in containers. It is essentially a thin wrapper around a pointer to a std::type_info
. std::type_index
is a C++11 feature.
Upvotes: 3
Reputation: 171097
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;
Upvotes: 12