Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Directly call a virtual method passed in template [duplicate]

Consider a simple example:

struct FooParent {
   virtual void bar() { }
};

struct Foo: FooParent {
   void bar() { }
};

int main() {
   Foo foo;
   void (Foo::*foo_member)() = &FooParent::bar;
   //(foo.*FooParent::foo_member)();
   foo.FooParent::bar();
}

As you can see one can use scope resolution on the foo object when calling bar member function while there is no way to explicitly declare the scope for member function pointer. I accept that the syntax should be prohibited when using ->* as the operator can be overloaded in sometimes unexpected way, but I cannot understand the reason behind preventing explicit scope resolution when dereferencing with .*.

I am trying to disable virtual dispatch for a member pointer that points to a base class's virtual function.

like image 900
W.F. Avatar asked Nov 15 '22 19:11

W.F.


1 Answers

The name of the variable you declared is foo_member, inside your local block scope. It is not a name Foo::foo_member, i.e. the class Foo has no member foo_member. By contrast, the name bar lives in the scope of the class Foo, and also in the scope of the class FooParent.

So the scope resolution mechanism works as expected: it resolves the scope.

[Update:] There is no mechanism to disable virtual dispatch through a member function pointer. You can call a member function of the base subobject like this:

 void (FooParent::*p)() = &FooParent::bar;
 (static_cast<FooParent&>(foo).*p)();

But the call still ends up getting dispatched virtually. The virtuality of the member function is baked into the member function pointer value. The next best thing you can do is to use a lambda:

auto q = [](FooParent & f) { f.FooParent::bar(); };
q(foo);
like image 182
Kerrek SB Avatar answered Dec 16 '22 12:12

Kerrek SB