开发者

How to detect non-virtual-override at compile or runtime

开发者 https://www.devze.com 2023-04-04 18:07 出处:网络
I want to detect if a function was (statically) overridden in a derived class: template< typename T >

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" <<开发者_如何学JAVA; 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.


Works here. BTW the easiest approach would be to define f() in A as empty:

struct A{ void func(){ } };


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 :(

0

精彩评论

暂无评论...
验证码 换一张
取 消