简体   繁体   English

我可以判断是否实现了 C++ 虚函数

[英]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我已经看到了这个,但它已经过时了,现在可能有一些 c++11/14 必须说的内容: 检测 C++ 虚函数是否已在派生类中重新定义的方法

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.然而,另一种方法是抛弃 C++ 自动运行时多态性,而是提供一个临时实现。 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.并且您可以检查函数指针是否等于默认值。

What comes to my mind right now is to have a special "counter" variable, which will take its value based on the implementation and zero if the base-class function is called.我现在想到的是有一个特殊的“计数器”变量,它会根据实现取值,如果调用基类函数则取零。 I think that this sounds a bit obsolete style though and try to find a better solution in a moment.我认为这听起来有点过时的风格,并尝试立即找到更好的解决方案。 See the example for now:现在看例子:

    struct Base
    {
        virtual void func(int x, int& implemented) {implemented = 0;}

    };

    struct Deriv : Base
    {
        virtual void func(int x, int& implemented) override {implemented = 1;}
    };

If the functions are void as in your example, you also can use "return codes" - just return implemented value back.如果函数在您的示例中是无效的,您也可以使用“返回代码” - 只需返回已实现的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM