tkn156 tkn156 - 14 days ago 7
C++ Question

c++ member functions with unresolved overload calling member functions

I'm trying to make an object with a member function that calls another member function like so

foo foo1 = new foo(1, 2);
foo1.print(printj);


I have class:

class foo
{
public:
foo(int x, int y) {i = x; j = y;};
void const print(void const f());
void const printi();
void const printj();
private:
int i;
int j;
}


and my implementation is something like:

void const foo::printi(){
std::cout << i;
}
void const foo::printj(){
std::cout << j;
}
void const foo::print(void const f()){
f();
}


I'm getting an error of
[Error] no matching function for call to 'foo::print()'

Why is that, and how can i fix it?

Answer

You need to:

  1. Declare the pointer-to-member function parameter as such:
    void const print(void const (foo::*f)());
  1. Pass the member function pointer correctly:
    foo1.print(&foo::printj);
  1. Call it with an actual instance (member function call requires an instance):
    void const foo::print(void const (foo::*f)()){
        (this->*f)();
    }

Alternatively you can make the instance an additional parameter or use std::bind or boost::bind to bind them together.

Comments