简体   繁体   English

C ++ 14和更高版本是否允许Lambda函数使用默认参数? 如果可以,怎么办?

[英]Does C++14 and above allow default parameters for Lambda functions? If so how?

Does lambda functions changes to accept default arguments in c++ 14? lambda函数是否更改为接受c ++ 14中的默认参数?

This example doesn't work on C++ 11: 此示例不适用于C ++ 11:

int main() {

    int i = 34;
    auto RectSurf = [i](int length = 0, int width = 0){ return length * width;};
    cout << RectSurf(10) << endl;


    std::cout << std::endl;
}

But it works fine on C++ 14 and above. 但是它在C ++ 14及更高版本上可以正常工作。 So is it correct or not? 如此正确与否? Because C++ prime 5ed said that: "Passing Arguments to a Lambda As with an ordinary function call, the arguments in a call to a lambda are used to initialize the lambda's parameters. As usual, the argument and parameter types must match. Unlike ordinary functions, a lambda may not have default arguments (§ 6.5.1, p. 236). Therefore, a call to a lambda always has as many arguments as the lambda has parameters. Once the parameters are initialized, the function body executes. 因为C ++ Prime 5ed表示:“将参数传递给Lambda与普通函数调用一样,对Lambda的调用中的参数用于初始化Lambda的参数。通常,参数和参数类型必须匹配。与普通函数不同,lambda可能没有默认参数(第6.5.1节,第236页),因此,对lambda的调用始终具有与lambda具有参数一样多的参数,一旦参数初始化,函数主体便会执行。

As an example of a lambda that takes arguments, we can write a lambda that behaves like our isShorter function:" From C++ Prime 5ed. 作为带有参数的lambda的示例,我们可以编写一个行为类似于isShorter函数的lambda:“来自C ++ Prime 5ed。

But the same code on C++14 and above works fine! 但是在C ++ 14及更高版本上使用相同的代码就可以了! But Also I've read here in SO That lambda functions can have a default parameter on condition that no variable has been captured in Lambda's capture list. 但是我也在SO中读到过,如果Lambda的捕获列表中没有捕获任何变量,则lambda函数可以具有默认参数。

Default Arguments in Lambda Expressions were explicitly added to the Standard with C++14, and were not permitted in C++11. Lambda表达式中的默认参数已通过C ++ 14明确添加到标准中,而在C ++ 11中则不允许。 You can see this if you run the code against two different compiler flags in GCC , one for C++11, one for C++14, and compile using the -Wpedantic flag, you'll see that when compiled for C++11, the compiler issues a warning (GCC still supports it, but tells you it's not standard-compliant) whereas in C++14, there's no warning. 如果您在GCC中针对两个不同的编译器标志运行代码,就可以看到这一点,一个针对C ++ 11,一个针对C ++ 14,然后使用-Wpedantic标志进行编译,您将看到针对C ++进行编译11,编译器发出警告(GCC仍然支持它,但是会告诉您它不符合标准),而在C ++ 14中,没有警告。

So yes. 是的 In C++14 and later, Default Arguments in a Lambda Expression are valid. 在C ++ 14和更高版本中,Lambda表达式中的默认参数有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM