要将std :: function变量设置为具有默认参数的lambda函数,我可以使用auto如下:
auto foo = [](int x = 10){cout << x << endl;};
foo();
Run Code Online (Sandbox Code Playgroud)
这将打印10.
但我希望foo变量驻留在结构中.在结构中我不能使用auto.
struct Bar
{
auto foo = [](int x = 10}(cout << x << endl}; //error: non-static data member declared ‘auto’
};
Bar bar;
bar.foo();
Run Code Online (Sandbox Code Playgroud)
auto用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(); …Run Code Online (Sandbox Code Playgroud)