typeid doesn't return correct type
cout << typeid(int&).name();
This, in my opinion, sh开发者_开发技巧ould return int&
as a type, not an int
, but on GCC 4.5.1 and on VS2010 SP1 beta it returns int
. Why is this?
This is how typeid is supposed to work. When you apply typeid
to a type-id of a reference type, the type_info
object refers to the referenced type.
ISO/IEC 14882:2003, 5.2.8 / 4 [expr.typeid]:
When
typeid
is applied to a type-id, the result refers to atype_info
object representing the type of the type-id. If the type of the type-id is a reference type, the result of thetypeid
expression refers to atype_info
object representing the referenced type. If the type of the type-id is a class type or a reference to a class type, the class shall be completely-defined. Types shall not be defined in the type-id.
Your first mistake is expecting anything useful from std::type_info::name()
. From the standard:
- §18.5.1/1: "The names, encoding rule, and collating sequence for types are all unspecified and may differ between programs."
- §18.5.1/7: "
const char* name() const;
Returns: an implementation-defined NTBS."
If you want a portable solution for meaningful (through not necessarily consistent) type names, I recommend using Boost.TypeIndex's boost::typeindex::type_id_with_cvr<>().pretty_name()
(reference).
The C++ spec does not guarantee that type_info::name
actually hands back the name of the type as it appears in the C++ source code; in fact, the spec, §18.5.1/7, only guarantees that the function hand back "an implementation-defined NTBS."
Consequently, there's no reason to assume that using typeid
to get the name of a type will actually hand back the name of the type as you'd expect it to.
The reason you're seeing the type of int
and not int&
is that the definition of typeid
says that it ignores references. To quote the spec, §5.2.8/4:
When typeid is applied to a type-id, the result refers to a type_info object representing the type of the type-id. If the type of the type-id is a reference type, the result of the typeid expression refers to a type_info object representing the referenced type.
(My emphasis)
This means that typeid(int&)
and typeid(int)
are completely identical to one another, hence the output being int
and not int&
or something related to it.
精彩评论