C++14 lambda 的默认参数类型推导取决于前面的参数

标签 c++ lambda c++14 language-lawyer default-parameters

这作为 C++14 是无效的吗?

auto f = [](auto x, auto y = std::decay_t<decltype(x)>{}) { };
f(0);

我原以为它大致相当于

auto f = [](int x, int y) { };
f(0, int{});

GCC 6.3 和 Clang 4.0 都不接受我的代码。

是不是跟我对C++模板推导阶段不了解有关?长达 1400 页的规范实际上对我的问题有明确的答案吗?

更新

总而言之,我的问题实际上可以简化为这段代码(没有 lambda,单个参数)并且在 C++14 下无效(感谢@BaummitAugen 和@NirFriedman)

template <typename T>
void f(T x = 0) { }

int main() {
    f();
}

最佳答案

编译器拒绝你的代码是正确的,它确实不是有效的 C++14。

在标准中(这里使用 N4141)我们有

For a generic lambda, the closure type has a public inline function call operator member template (14.5.2) whose template-parameter-list consists of one invented type template- parameter for each occurrence of auto in the lambda’s parameter-declaration-clause, in order of appearance.

(5.1.2/4 [expr.prim.lambda])。所以你的调用相当于调用了一些

template <class T1, class T2>
auto operator() (T1 x, T2 y = std::decay_t<decltype(x)>{});

现在

If a template parameter is used only in non-deduced contexts and is not explicitly specified, template argument deduction fails.

(14.8.2/4 [temp.deduct.type]) 和

The non-deduced contexts are:
[...]
- A template parameter used in the parameter type of a function parameter that has a default argument that is being used in the call for which argument deduction is being done.

(14.8.2/5 [temp.deduct.type]) 使您的调用格式错误。

关于C++14 lambda 的默认参数类型推导取决于前面的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42240849/

相关文章:

python - 使用 lambda 函数作为 dict 值时发生奇怪的覆盖

c++ - 访问元组 vector 中的元素 C++

C++命令行参数验证

c++ - 如何定义指向函数指针的指针以及如何在 C++ 中使用它?

c++ - 派生纯虚函数的实现

scala - 为什么不能在字符串插值中使用 _ ?

c++ - 使用通配符与 FindWindow api 调用与 mfc

c++11 - 返回 lambda 捕获函数参数引用

c++ - nonptr-new-declarator 中的错误表达式

c++ - placement new 如何知道要创建哪个布局?