We have a subproject 'commonUtils' in which there are many common code snippets used in the parent project. One such interesting thing that I saw was: -
/********************************************************************* 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; }
I believed the comment and thought it was a pretty interesting template, although this is not used throughout the project. I tried to use this just for curiosity ...
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";
But not one of them ever returns the truth. MSVC 2005 does not give any warnings, but Comeau warns that the typeid expression has no effect. Section 5.2.8 in the C ++ standard does not say anything similar to what the comment says, i.e. typeid is evaluated at compile time for non-polymorphic types and at runtime for polymorphic types.
1) So I think the comment is misleading / just wrong, or since the author of this code is a pretty senior C ++ programmer, did I miss something?
2) GTR, I wonder if we can check if the class is polymorphic (has at least one virtual function) using some kind of technique?
3) When would one know if a class is polymorphic? Rough assumption; to get the starting address of the class using dynamic_cast<void*>(T) (since dynamic_cast only works with polymorphic classes).
Waiting for your opinion.
Thanks in advance,
c ++ polymorphism templates
Abhay
source share