Hi-Angel
Hi-Angel

Reputation: 5619

Give a closure as a «class method pointer»?

Okay, that should be simple, basically the example below should have worked (at least be compiled):

class Foo {
public:
    void DoNothing( void(Foo::*funcptr)() ){}
    void CallDoNothing();
};

void Foo::CallDoNothing(){
    auto closure = [this](){};
    DoNothing(closure);
}

int main(){
    return 0;
}

But for some reason that triggers a compilation error

test.cpp: In member function ‘void Foo::CallDoNothing()’:
test.cpp:9:19: error: no matching function for call to ‘Foo::DoNothing(Foo::CallDoNothing()::__lambda0&)’
  DoNothing(closure);
                   ^
test.cpp:9:19: note: candidate is:
test.cpp:3:7: note: void Foo::DoNothing(void (Foo::*)())
  void DoNothing( void(Foo::*funcptr)() ){}
       ^
test.cpp:3:7: note:   no known conversion for argument 1 from ‘Foo::CallDoNothing()::__lambda0’ to ‘void (Foo::*)()’

I am already even tried to cast: DoNothing(reinterpret_cast< void(Foo::*funcptr)() >(closure));, DoNothing(( void(Foo::*funcptr)() )closure);, plus some variations on this — these all just triggered a compilation errors!

Upvotes: 0

Views: 162

Answers (1)

Jens
Jens

Reputation: 9406

Why do you think that a lambda function can be assigned to a member function pointer? A lambda function is of some anonymous type. It is assignable to function pointers only if it has an empty capture, but even that is not compatible with a member function pointer as in your example.

You can use std::function<void ()> or make DoNothing a template function.

Upvotes: 2

Related Questions