virtual call to base class method
I want to use std::bind
and do non-virtual call to base class function eg: derived_obj.BaseClass::foo()
Example:
Let's say I have base class A and derived class B . A has a virtual function foo()
which is overridden by B .
class A
{
public:
virtual void foo() { std::cout << "Hello from A::foo()!";}
}
class B : public A
{
public:
void foo() overide { std::cout << "Hello from B::foo()!";}
}
If I want to call A::foo()
from object of class B I do non-virtual call:
B b_obj;
b_obj.A::foo(); // prints "Hello from A::foo()!"
Now I want to use std::bind
and do non-virtual call to A::foo()
from b_obj, how do I do this?
I've already tried by casting b_obj
to A and use address of &A::foo()
, but had no luck.
auto f = std::bind(&A::foo, static_cast<A*>(&b_obj));
f(); // prints "Hello from B::foo()!" but it should print "Hello from A::foo()!"
You have two options here. You should either do the non-virtual call in a lambda or you go the trusty old way of slicing the object (which is a copy) you want to pass to std::bind
.
// Base method
B b_obj; b_obj.A::foo(); // prints "Hello from A::foo()!"
// First method
auto k = [](auto b){ b.A::foo(); };
k(b_obj);
// Second method
auto f = std::bind(&A::foo, *static_cast<A*>(&b_obj));
f();
This all prints:
Hello from A::foo()!
Hello from A::foo()!
Hello from A::foo()!
The Second method works (slices) since std::bind
copies its arguments. You should really prefer a lambda.
You could wrap the call inside a lambda:
B b_obj;
auto f = std::bind([&b_obj]() { b_obj.A::foo(); } );
But this makes little sense unless you can only use std::bind
somewhere (for example because of std::is_bind_expression
), as you pass the object parameter to the lambda's capture, not to bind.
Otherwise just using a lambda or std::function
without bind
should be cleaner.
下一篇: 虚拟调用基类方法