To set a std::function variable to a lambda function with default argument I can use auto
as in:
auto foo = [](int x = 10){cout << x << endl;};
foo();
This will print 10.
But I want the foo variable to reside in a struct. In a struct I cannot use auto
.
struct Bar
{
auto foo = [](int x = 10}(cout << x << endl}; //error: non-static data member declared ‘auto’
};
Bar bar;
bar.foo();
Replacing auto
with std::function
struct Bar
{
std::function<void(int x = 10)> foo = [](int x = 10}(cout << x << endl}; //error: default arguments are only permitted for function parameters
};
Bar bar;
bar.foo();
or
struct Bar
{
std::function<void(int)> foo = [](int x = 10}(cout << x << endl};
};
Bar bar;
bar.foo(); //error: no match for call to ‘(std::function<void(int)>) ()’
Without the struct and replacing auto
for std::function:
std::function<void(int x)> foo = [](int x = 10){cout << x << endl;};
foo(); //error: no match for call to ‘(std::function<void(int)>) ()’
So how should I declare foo?