My question is about using std::function to class methods. Suppose I have the following class hierarchy:
class Foo { public: virtual void print() { cout << "In Foo::print()" << endl; } virtual void print(int) { cout << "In Foo::print(int)" << endl; } }; class Bar : public Foo { public: virtual void print() override { cout << "In Bar::print()" << endl; } virtual void print(int) override { cout << "In Bar::print(int)" << endl; } } Now there is another function which is supposed to dynamically call one of the two class methods depends on its input:
void call(Foo* foo, void (Foo::*func)(void)) { (foo->*func)(); } Foo* foo = new Foo(); Bar* bar = new Bar(); call(foo, &Foo::print); call(bar, &Foo::print); When I compile the above code snippet using g++/clang++, it works as expected, where the output is:
In Foo::print() In Bar::print() My questions are then:
since there are two functions (overloaded) with the same name: print, when I pass the address of class function:
&Foo::print, how did the compiler know that I am actually callingFoo::print(void)but notFoo::print(int)?is there another way that I can generalize the code above such that the second parameter of
void call(Foo*, xxx)can be passed using bothFoo::print(void)andFoo::print(int)is there anyway to achieve this feature using new feature in C++11
std::function? I understand that in order to usestd::functionwith a non-static class method, I have to usestd::bindto bind each class method with a specific class object, but that would be too inefficient for me because I have many class objects to be bound.
call(Foo* foo, void (Foo::*func)(void)), thus you'll get(void)overload&Foo::printwhen passing the argument, how did the compiler decide which to pass?