Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

c++11 - Can I tell if a C++ virtual function is implemented

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) { <default behavior here> }
    virtual void func2(int x) { <default behavior here> }
};

struct Deriv : Base
{
    virtual void func(int x) override { <new behavior here> }
};

int main()
{
    Base *d = new Deriv;

    if(implements<Base::func(int)>(d)) // This should evaluate true
    {} 

    if(implements<Base::func2(int)>(d)) // This should evaluate false
    {}
}

I have seen this but it's dated and there might be a something that c++11/14 has to say now: Ways to detect whether a C++ virtual function has been redefined in a derived class

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...