Search code examples
c++function-pointers

argument of type "void" is incompatible error


hello and thanks in advance for supporting,

I'm trying to send a pointer to function which is type void and receive nothing.

it didn't work well so far.

here is my minimal code that have this problem:

void func::foo()
{
    return;
}

and the function which use it is:

void func::create_func(void(*wanted_func)())
{
    wanted_func();
}

the problem is when it called:

create_func(foo);

please advice, I hope i haven't asked something that is very silly


Solution

  • From what I understand, you'd like to pass a member method pointer to another member method. So you'll have to bind an object instance to the method that you want to pass. Have a look at std::bind (Reference)

    Here is a minimal example which I believe does what you want:

    #include <iostream>
    #include <functional>
    
    class Func {
     public:
        void foo() {
          std::cout << "called foo\n";
        }
        
        void create_func(std::function<void()> functor) {
            functor();
        }
    
    };
    
    int main() {
        Func f;
        f.create_func(std::bind(&Func::foo, f));
        return 0;
    }