我可以告诉是否实现一个C ++虚拟函数 [英] Can I tell if a C++ virtual function is implemented

查看:117
本文介绍了我可以告诉是否实现一个C ++虚拟函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想能够在运行时告诉一个类的实例是否实现了一个虚函数。例如:

  struct Base 
{
virtual void func(int x){< default behavior这里> }
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))//这应该求值真
{}

if :: func2(int)>(d))//这应该评价为false
{}
}

我已经看到这个,但它已过时,可能有一些c ++ 11/14现在必须说:
方法来检测是否一个C ++虚拟函数已经在派生类中重新定义< a>

简单的答案是:不。并不是以便携式的方式。



更长的答案:实际上,多态性的目标是使其与功能来源的用户无法区分。



即使开发人员不编写代码,编译器可能仍然为派生类生成专用版本的函数(用于更好的优化)。这将抛弃甚至非可移植的实现,它将检查虚拟表...



一个替代的路由,但是,将抛弃C ++自动运行时多态而是提供ad-hoc实现。例如,如果你提供自己的虚拟表/指针机制,那么你将有更多的控制:

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

FuncType func;
Func2Type func2;
};

,你可以检查函数指针是否等于默认值。 p>

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

解决方案

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.

这篇关于我可以告诉是否实现一个C ++虚拟函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆