0

I'd like to understand why the following works:

class Foo {
public:
    using Callback = std::function<void(std::string& string)>;

    void setCallback(Callback&& callback) { windowInfo = callback; };
private:
    Callback windowInfo;
};

class Bar {
    Bar() { foo->setCallback([this](std::string& e) { sayHello(e); });}
    void sayHello(std::string& name) { //do something }

    Foo* foo;
};

Foo::setCallback asks for a function with no captures, however, I'm passing a lambda that captures Bar. I would expect the compiler to complain void(Bar, string) != void(string). Since I'm passing in a member function, it must implicitly pass the $this parameter as the first argument. Making the function signatures not equivalent.

EDIT

Why is that when I redefine using EventCallback as using EventCallback = void(Event& event); suddently this doesn't work anymore "no viable conversion from Application.cpp:10:34 to Foo::Callback aka (...)

Is std::function acting as the "glue" holding a reference to Bar but exposing the correct signature when requested?

frankelot
  • 13,666
  • 16
  • 54
  • 89
  • 1
    "*Foo::setCallback asks for a function with no captures*" No, it asks for any object callable with that signature. That's what `std::function` *does*. "*Since I'm passing in a member function*" Where? I see no code where you're getting a pointer to a member. – Nicol Bolas Aug 29 '20 at 14:54
  • 1
    Not the answer, but `setCallback` should probably be rewritten as `void setCallback(Callback callback) {windowInfo = std::move(callback);};`. – HolyBlackCat Aug 29 '20 at 14:59
  • 1
    Even if you don't change the signature, you should still use `windowInfo = std::move(callback);` as rvalue references aren't rvalues. – Mike Vine Aug 29 '20 at 15:02
  • Thanks for your answers, I updated my question. I think I'm having trouble understanding what's the difference between lambdas and std::functions – frankelot Aug 29 '20 at 16:02
  • Would it be right to think of "lambdas" as "classes" where the captures are the data members, and with an `operator()(xxx)` overload, where xxx in my case is 'Event'. Is std::function some kind of "boxed" lambda? – frankelot Aug 29 '20 at 16:15

0 Answers0