我们有一个子项目“commonUtils”,其中有许多在父项目中使用的通用代码片段。我看到的一件有趣的事情是:-
/*********************************************************************
If T is polymorphic, the compiler is required to evaluate the typeid
stuff at runtime, and answer will be true. If T is non-polymorphic,
the compiler is required to evaluate the typeid stuff at compile time,
whence answer will remain false
*********************************************************************/
template <class T>
bool isPolymorphic() {
bool answer=false;
typeid(answer=true,T());
return answer;
}
我相信评论并认为它是一个非常有趣的模板,尽管它没有在整个项目中使用。我只是出于好奇而尝试这样使用它...
class PolyBase {
public:
virtual ~PolyBase(){}
};
class NPolyBase {
public:
~NPolyBase(){}
};
if (isPolymorphic<PolyBase>())
std::cout<<"PolyBase = Polymorphic\n";
if (isPolymorphic<NPolyBase>())
std::cout<<"NPolyBase = Also Polymorphic\n";
但是这些都没有返回true。MSVC 2005 未给出警告,但 Comeau 警告 typeid 表达式无效。C++ 标准中的第 5.2.8 节没有像注释所说的那样说任何东西,即 typeid 在编译时对非多态类型进行评估,在运行时对多态类型进行评估。
1)所以我猜这个评论是误导/完全错误的,或者因为这段代码的作者是一个相当资深的 C++ 程序员,我错过了什么吗?
2)OTOH,我想知道我们是否可以使用某种技术测试一个类是否是多态的(至少具有一个虚函数)?
3) 什么时候想知道一个类是否是多态的?胡乱猜测; 通过使用获取类的起始地址dynamic_cast<void*>(T)
(dynamic_cast
仅适用于多态类)。
等待您的意见。
提前致谢,