将lambda函数指定为默认参数

mav*_*vam 33 c++ lambda c++11

如何将lambda指定为默认参数?我想这样做:

int foo(int i, std::function<int(int)> f = [](int x) -> int { return x / 2; })
{
    return f(i);
}
Run Code Online (Sandbox Code Playgroud)

但我的编译器(Mac OS X上的g ++ 4.6)抱怨:

error: local variable 'x' may not appear in this context
Run Code Online (Sandbox Code Playgroud)

编辑:的确,这是一个编译器错误.上面的代码适用于最新版本的gcc(4.7-20120225).

Tim*_*ter 27

你可以使用重载:

int foo(int i)
{
    return foo(i, [](int x) -> int { return x / 2; });
}

int foo(int i, std::function<int(int)> f)
{
    return f(i);
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*esD 8

这似乎是gcc中的一个错误; 只要没有捕获任何内容,该标准就允许在默认参数中使用lambda表达式.

以下似乎是FDIS在默认参数中所说的关于lambdas的所有内容,因此默认情况下应允许除此之外禁止使用的任何其他用途.

C++ 11 FDIS 5.1.2/13

出现在默认参数中的lambda表达式不得隐式或显式捕获任何实体.

[例如:

void f2() {
    int i = 1;
    void g1(int = ([i]{ return i; })());       // ill-formed
    void g2(int = ([i]{ return 0; })());       // ill-formed
    void g3(int = ([=]{ return i; })());       // ill-formed
    void g4(int = ([=]{ return 0; })());       // OK
    void g5(int = ([]{ return sizeof i; })()); // OK
}
Run Code Online (Sandbox Code Playgroud)

- 结束例子]

  • 请注意,在所有这些示例中都没有参数,这就是编译器阻塞的内容(即使在VS2010中). (2认同)
  • 这些示例略有不同 - 这些是*执行*lambda*以获取*函数参数的默认值; 这真的意味着lambda本身可以是默认值吗? (2认同)