如何在编译或运行时检测非虚拟覆盖
我想检测一个函数是否在派生类中被(静态)重写:
template< typename T >
struct A{ void func(){ static_cast<T*>(this)->func(); } };
struct B: A<B>{};
struct C: A<C>{ void func(){ std::cout << "class C" << std::endl; };
C c;
if(&A<C>::func != &C::func)
c.func();
显然,如果它没有重写,我不会调用“func”。 我更喜欢直接回答我的问题。讲述实际问题以确定超载。 我也将感谢任何显示解决一般问题的其他方法的答案。
好的,它可以编译,我还没有找到与我的实际代码的差异,但没有。 顺便说一句,在我的实际代码中,我不仅仅是试图避免调用该函数,还有更多。我真的很想知道该函数是否被覆盖,或者我是否需要使用完全不同的方法。
I want to detect if a function was (statically) overridden in a derived class:
template< typename T >
struct A{ void func(){ static_cast<T*>(this)->func(); } };
struct B: A<B>{};
struct C: A<C>{ void func(){ std::cout << "class C" << std::endl; };
C c;
if(&A<C>::func != &C::func)
c.func();
Obviously, I won't call 'func' if it has no override.
I prefer direct answers to my questions. Telling about the actual problem to determine the overloading.
I will also appreciate any answer that shows other ways to approach the general problem.
Ok, it compiles, I have yet to find the difference to my actual code, that didn't.
By the way, in my actual code, I am not just trying to avoid calling the function, there is some more. I really want to know if the function is overridden, or if I need to use a completely different method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在此处工作。顺便说一句,最简单的方法是将
A
中的f()
定义为空:Works here. BTW the easiest approach would be to define
f()
inA
as empty:我不知道有什么方法可以完成您具体要求的操作,但是您可以使用一些很酷的模式来使用模板实现“静态多态性”。这消除了您在运行时对使用 v 表的依赖(实际上,没有一个用于实现类似多态的效果)。因此,您应该能够在编译时检查您需要的函数是否可用。
维基百科模板元语法条目上有一些关于它的介绍:
http://en.wikipedia.org/wiki/Template_metaprogramming
它会让你的代码更加复杂,所以我认为你应该考虑一个不需要这个功能的重新设计 - 它更多的是一个反射属性,而 C++ 不是很到目前为止还很擅长:(
I don't know any way to do what you're asking specifically, but you can use some cool patterns to achieve "static polymorphism" using templates. This removes your dependency on using the v-table during runtime (really, there isn't one used to achieve the polymorphic-like effect). So, you should be able to check at compile time if the functions you need are available.
There's a little intro about it on wikipedias template metagrogramming entry:
http://en.wikipedia.org/wiki/Template_metaprogramming
It will make your code more complex though, so i think you should just think about a redesign that doesn't require this feature - its more of a reflection attribute and C++ isn't very good at that as of yet :(