我希望能够在运行时知道类的实例是否实现了虚函数。例如:
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
{}
}
我已经看到了,但是它已经过时了,现在c ++ 11/14可能不得不说些什么:检测派生类中是否已重新定义C ++虚拟函数的方法
简短的答案是:否。当然不是以可移植的方式。
更长的答案:实际上,多态性的真正目的是使它与功能来源的用户无法区分。
即使开发人员不编写代码,编译器仍可能为派生类生成该函数的专用版本(以实现更好的优化)。这甚至会抛出将检查虚拟表的非便携式实现。
但是,另一种方法是放弃C ++自动运行时多态性,而是提供即席实现。例如,如果您要提供自己的虚拟表/指针机制,那么您将拥有更多控制权:
struct VirtualTable {
typedef void (*FuncType)(void*, int);
typedef void (*Func2Type)(void*, int);
FuncType func;
Func2Type func2;
};
您可以检查函数指针是否等于默认值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句