int main() {
const int a = 2;
auto f = [&](auto b) { std::cout << a << ", " << b << std::endl; };
f(3);
}
Don't know if it should work with std::function
but this works for sure.
Further investigation:
I created a class to mimic as closely as possible the lambda:
class Functor {
private:
int const x;
public:
Functor() : x{24} {}
auto operator()(int b) const -> void { cout << x << " " << b << endl; }
};
std::function<auto(int)->void> f2 = Functor{};
f2(3); // <- this works
This suggests that your example should have worked. After all lambdas are the same in behavior with an object who has the operator()
overloaded and fields for the captured variables.
If we change the class to get to the auto
part:
This doesn't work:
class Functor {
private:
int const x;
public:
Functor() : x{24} {}
auto operator()(auto b) const -> void { cout << x << " " << b << endl; }
};
std::function<auto(int)->void> f2 = Functor{}; // <-- doesn't work
However this works:
class Functor {
private:
int const x;
public:
Functor() : x{24} {}
template <class T>
auto operator()(T b) const -> void { cout << x << " " << b << endl; }
};
std::function<auto(int)->void> f2 = Functor{}; // <-- this works
So most likely it is related to the use of auto
as parameter of lambda/functions, a feature new to C++14 so most likely without a mature implementation.