Does the class have a virtual function? C ++

Therefore, I have a class and you want to determine if it has a virtual function or not.

The first method that I considered during dynamic conversion.

class A { // hidden details.. }; class B:public A{}; int main() { A *a = new A;; B* b = dynamic_cast<B*>(a); } 

So, in this case, if there is a virtual function in class A, the compilation will succeed, otherwise this error will occur:

Error: dynamic_cast \ u2018a \ u2019 (type \ u2018class A * \ u2019) cannot enter \ u2018class B * \ u2019 (source type is not polymorphic)

Is there a way to check this without a compilation error? NOTE. I don't have C ++ 11 or boost support!

+6
source share
1 answer

You can check for virtual methods by comparing the type size with the type of the type with the added virtual method. This type of validation is not guaranteed by the standard and can be tricked by virtual inheritance, so it should not be used in production code. However, it can be useful for simple cases where C ++ 11 std::is_polymorphic not available. Tested under g ++ 4.6:

 template<typename T> class VirtualTest: private T { virtual void my_secret_virtual(); }; template<typename T> bool has_virtual() { return sizeof(T) == sizeof(VirtualTest<T>); } 

Call the test as has_virtual<A>() .

+8
source

Source: https://habr.com/ru/post/970623/


All Articles