0

I am having some trouble with passing a function that is a member of the class 'F' to a function that is the member of class 'X'.I get the error 'error: no match function for call to X::call()' Sorry if the solution is really simple, I'm still fairly new to C++

My code:

#include <iostream>

using namespace std;

class X{
public:
    void call (void (*func)()){
        func();
    }
};

class F{
public:
    void Function(){
        cout<<"hello";
    }
};

int main()
{
    X x;
    F f;

    x.call(f.Function);

    return 0;
}

basically I'm just trying to pass the function from class F into class X call function.

Thanks in advance for your help.

Egg42
  • 65
  • 5
  • 2
    member function != regular function, make `F::Function` `static`. – Jarod42 Nov 22 '20 at 08:34
  • You tagged your question with `member-function-pointers` but `void (*func)()` is a regular function pointer not a member function pointer. A member function pointer (of the class F) would be `void (F::*func)()`. – john Nov 22 '20 at 08:38

1 Answers1

0

The main problem is something that any decent text-book, tutorial or class should have mentioned: A non-static member function is not like a non-member function. The difference being that a (non-static) member function needs an object to be called on, and non-member functions doesn't. This makes the pointers to each very different.

You could solve your problem with e.g. std::function:

void call(std::function<void()> func);

Then pair it with a lambda expression:

x.call([&]()
{
    f.function();
});

As an alternative, you could use templates for the function type:

template<typename F>
void call(F func);

If you use a template, you can also use std::bind:

x.call(std::bind(&F::Function, f));

For completeness, here's the other alternatives mentioned in comments:

  • The first suggest making F::Function a static member function, which means it's a member of the class and don't need any specific object to be called:

    static void Function();
    
  • The second comment suggest creating a pointer to a F member function:

    class F;  // Forward declare the F class
    
    class X
    {
    public:
        void call(void (F::*func)());
    };
    
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621