【发布时间】:2014-05-19 22:53:26
【问题描述】:
要将 std::function 变量设置为带有默认参数的 lambda 函数,我可以使用 auto,如下所示:
auto foo = [](int x = 10){cout << x << endl;};
foo();
这将打印 10。
但我希望 foo 变量驻留在结构中。在结构中我不能使用auto。
struct Bar
{
auto foo = [](int x = 10}(cout << x << endl}; //error: non-static data member declared ‘auto’
};
Bar bar;
bar.foo();
用 std::function 替换 auto
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();
或
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)>) ()’
没有结构并替换 auto 为 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)>) ()’
那么我应该如何声明 foo?
【问题讨论】:
-
无法使用默认参数创建
std::function。
标签: c++ c++11 lambda std-function