Can I tell if a C++ virtual function is implemented

后端 未结 2 615
遇见更好的自我
遇见更好的自我 2020-12-12 05:12

I want to be able to tell at run-time if an instance of a class implements a virtual function. For example:

struct Base
{
    virtual void func(int x) { <         


        
2条回答
  •  难免孤独
    2020-12-12 06:03

    The short answer is: No. And certainly not in a portable manner.

    The longer answer: actually, the very goal of polymorphism is to make it indistinguishable to the user where the functionality comes from.

    Even if the developer does not write code, the compiler might still generate a dedicated version of the function for the derived class (for better optimization). This would throw off even non-portable implementations that would inspect the virtual tables...

    An alternative route, however, would be to throw off C++ automatic run-time polymorphism and instead provide an ad-hoc implementation. If for example you were to provide your own virtual table/pointer mechanism, then you would have more control:

    struct VirtualTable {
        typedef void (*FuncType)(void*, int);
        typedef void (*Func2Type)(void*, int);
    
        FuncType func;
        Func2Type func2;
    };
    

    and you could check whether the function pointer is, or is not, equal to the default.

提交回复
热议问题