typeid / type_info 奇怪的行为
typeid / type_info strange behaviour
为什么下面的例子:
#include <iostream>
#include <typeinfo>
template<typename T>
void fun(const T& param)
{
std::cout << "T = " << typeid(T).name() << std::endl;
std::cout << "param = " << typeid(param).name() << std::endl;
std::cout << (typeid(T)==typeid(param)) << std::endl;
}
int main(int, char**)
{
fun(1);
}
给出以下输出:
T is i
param is i
1
我知道 type_info::name()
行为依赖于实现。无论如何,我希望 operator==
到 return false
(因为 param
是一个常量引用而不是整数)。
标准中是这样定义的:
5.2.8/5: If the type of the expression or type-id is a cv-qualified type, the result of the typeid expression refers to a
std::type_info object representing the cv-unqualified type [Example:
class D { /* ... */ };
D d1;
const D d2;
typeid(d1) == typeid(d2); // yields true
typeid(D) == typeid(const D); // yields true
typeid(D) == typeid(d2); // yields true
typeid(D) == typeid(const D&); // yields true
—end example ]
为什么下面的例子:
#include <iostream>
#include <typeinfo>
template<typename T>
void fun(const T& param)
{
std::cout << "T = " << typeid(T).name() << std::endl;
std::cout << "param = " << typeid(param).name() << std::endl;
std::cout << (typeid(T)==typeid(param)) << std::endl;
}
int main(int, char**)
{
fun(1);
}
给出以下输出:
T is i
param is i
1
我知道 type_info::name()
行为依赖于实现。无论如何,我希望 operator==
到 return false
(因为 param
是一个常量引用而不是整数)。
标准中是这样定义的:
5.2.8/5: If the type of the expression or type-id is a cv-qualified type, the result of the typeid expression refers to a std::type_info object representing the cv-unqualified type [Example:
class D { /* ... */ }; D d1; const D d2; typeid(d1) == typeid(d2); // yields true typeid(D) == typeid(const D); // yields true typeid(D) == typeid(d2); // yields true typeid(D) == typeid(const D&); // yields true
—end example ]