Call a virtual function statically via a function pointer

Please consider the following code.

#include <iostream>
#include <memory>

struct A {
  A() {}
  virtual void f() {
    std::cout << "A::f" << std::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 method B::funtil the stack runs out, while I would like the method to callcall A::f. That is, he should call it statically, as is usually the case, if I just wrote:

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

The reason I want to have a method callis to specify some code before and after the “static call”, which is common to several methods with the same signature as f...

How can I statically call a virtual function defined at runtime?

+5
source share
2

. A , , ( ) , A:: f .

:: .

$10.3/12- " (5.1) ."

+4

, , . , , , - , , . ++ 0x, , IMO.

, , pre/post-functions, : "- > ".

+1

All Articles