开发者

Calling a virtual function statically through a function pointer

Please consider the following code.

#include <iostream>
#include <memory>

struct A {
  A() {}
  virtual void f() {
    std::cout << "A::f" << std开发者_JAVA技巧::endl;
  }
private:
  A(const A&);
};

struct B : public A {
  virtual void f() {
    std::cout << "B::f" << std::endl;
    call(&A::f);
  }
private:
  void call(void (A::*aMethod)()) {
    // ...
    (static_cast<A&>(*this).*aMethod)();
    //(static_cast<A>(*this).*aMethod)();  -> not allowed to copy!
    // ...
  }
};

void main() {
  std::auto_ptr<B> b (new B);
  b->f();
}

This code recursively calls the same B::f method until it runs out of stack, while I would like the call method to call A::f. That is, it should call it statically as it would normally happen had I simply written:

struct B : public A {
  virtual void f() {
    std::cout << "B::f" << std::endl;
    // ...
    A::f();
    // ...
  }
};

The reason I want to have the call method is to factor some code before and after the 'static call' that is common to several methods with the same signature as f...

How can I statically call a virtual function decided at run-time?


That's expected. The object expression is a Reference to the Base class A and hence virtual function mechanism (dynamic binding) is triggered as A::f is virtual.

Only the :: operator can supperess virtual function call mechanism.

$10.3/12- "Explicit qualification with the scope operator (5.1) suppresses the virtual call mechanism."


Your override is resolved when you take the pointer, so what you want here is not easily possible this way. The best thing you can do is a wrapper that calls your function - either something external, or a non-virtual function that calls your function. If you have C++0x features, you could use a lambda which is the cleanest solution IMO.

You might wanna rethink the way you do pre/post-functions as another way to tackle your problem: They can be implemented by overloading the "->" operator.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜