C ++ 14 lambda的默认参数类型推导取决于先前的参数 [英] C++14 lambda's default argument type deduction depending on preceding arguments

查看:160
本文介绍了C ++ 14 lambda的默认参数类型推导取决于先前的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是C ++ 14版本吗?

Is this not valid as 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都不接受我的代码.

Neither GCC 6.3 nor Clang 4.0 accepted my code.

  • http://ideone.com/b7b4SK GCC
  • http://ideone.com/EyLYaL Clang

这与我对C ++模板推导阶段缺乏了解有关吗?长达1400页的规格实际上对我的问题有明确的答案吗?

Is it related to my lack of understanding of C++ template deduction phases? Does the 1400 pages long spec actually has an explicit answer to my question?

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

To summarize, my problem can in fact be reduced to this piece of code (free of lambda, single parameter) and it is invalid under C++14 (thanks @BaummitAugen and @NirFriedman)

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

int main() {
    f();
}

推荐答案

编译器正确拒绝了您的代码,这实际上不是有效的C ++ 14.

The compilers are correct to reject your code, it is indeed not valid C++14.

在标准(此处使用N4141)中,

In the standard (using N4141 here) we have

对于通用lambda,闭包类型具有公共内联函数调用 操作员成员模板(14.5.2),其template-parameter-list由一种发明的类型template- 在lambda的parameter-declaration-clause中,按出现顺序为每次出现auto设置参数.

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]).因此,您的通话等同于拨打某些电话

(5.1.2/4 [expr.prim.lambda]). So your call is equivalent to a call to some

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])和

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

非推论上下文是:
[...]
-具有默认参数的函数参数的参数类型中使用的模板参数 用于进行参数推导的调用中.

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])使您的通话格式不正确.

(14.8.2/5 [temp.deduct.type]) makes your call ill-formed.

这篇关于C ++ 14 lambda的默认参数类型推导取决于先前的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆