C ++ 20模板lambas的局限性和用途 [英] limits and uses of C++20 template lambas

查看:67
本文介绍了C ++ 20模板lambas的局限性和用途的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关C ++标准专家的几个相关问题.

A couple of related questions for C++ standard gurus.

传入的C ++ 20 引入模板lambdas(

The incoming C++20 introduces template lambdas (P0428R2).

所以不是

auto x = [](auto x, auto y){ return x+y; };

我们可以如下指定模板参数

we can specify the template parameter as follows

auto x = []<typename T>(T x, T y){ return x+y; };

到目前为止,很好.

第一个问题:模板lambda中的显式模板参数只能从参数推导出,还是可以添加未推导的模板参数?

First question: can explicit template parameters, in template lambdas, only be deduced from arguments, or is it possible to add non-deduced template arguments?

阅读P0428r1我没有看到任何明确的限制,但是也没有看到未推导的模板参数的示例.

Reading P0428r1 I don't see any explicit limitations but, also, I don't see examples of non-deduced template arguments.

在第一近似中,我认为未推导的模板参数是合法的,因为我看到以下愚蠢的代码

In first approximation I suppose that non-deduced template arguments are legal because I see that the following silly code

int main()
 {   
   []<int = 0>(){ }();
 }

编译并运行g ++(10.0.0头)和clang ++(10.0.0头).

compiles and runs with both g++ (10.0.0 head) and clang++ (10.0.0 head).

假设允许使用非推导的模板参数,第二个问题是:在提供模板参数的同时如何调用模板lambda?

Supposing that non-deduced template parameters are allowed, the second question is: how can I call a template lambda while providing a template parameter?

例如:给定以下模板lambda

By example: given the following template lambda

auto x = []<std::size_t I>(auto t){ return std::get<I>(t); };

在不显式命名 operator()的情况下调用这样的Lambda 时是否存在一些用于指定模板参数 I 的语法?

Is there some syntax for specifying the template parameter I when invoking such lambdas without explicitly naming operator()?

我尝试过

x<0u>(y);

,但< 被解释为关系运算符.

but the < is interpreted as a relational operator.

我尝试过简单地添加 template

x template <0u>(y);

但它不起作用.

推荐答案

lambda函数中的模板标头没有特殊限制.毕竟,Lambda只是任何 operator()重载所能完成的工作的简写.

There are no special restrictions on template headers in lambda functions. Lambdas are after all just shorthand for what you could do already with any operator() overload.

当调用lambda函数的 operator()时,没有提供模板参数的特殊语法.如果您有无法推导的模板参数,则必须使用传统机制来提供那些模板参数.IE: lamb.operator()< Args>(...).

There is no special syntax for providing template arguments when invoking the operator() of a lambda function. If you have template parameters which are not deduced, you will have to use the traditional mechanisms for providing those template arguments. IE: lamb.operator()<Args>(...).

这篇关于C ++ 20模板lambas的局限性和用途的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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