For std::function<float()> func you declare func as a functor that returns a float , not a float& . As the error message says, the temporary float returned by func() cannot be bound to the non-console lvalue reference.
The above declaration does not match the signature of A::operator() , which ends. But keep in mind that if you change the type to std::function<float&()> func so that it matches the signature of A::operator() , the compilation error could be overturned, but then we will return the link to the local variable, which will lead to UB.
Note that for std::function<float()> func = a; std :: function is initialized with a copy of a . Then func() will return the link associated with member a wrapped in func , which is a local variable. And the link will dangle when you exit the foo function.
How to fix this depends on your design, change auto& foo() to auto foo() , i.e. passing the return value by copying will avoid UB here.
source share