如何调用 lambda 模板? [英] How to invoke a lambda template?

查看:41
本文介绍了如何调用 lambda 模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够用 gcc 编译以下代码:

template自动功能(包... x){返回 (x + ...) ;}模板auto lamd = [](Pack ... x) {返回 (x + ...) ;};

我可以使用 func(1,2,3) 调用函数模板,但是在调用 lambda 时出现错误,使用 lamd(1,2,3)lamd(1,2,3).

解决方案

第二个定义是变量模板.它没有将 lambda 的 operator() 定义为模板,而是采用 operator() 的参数类型的参数包.结果 operator() 是实例化变量的闭包类型的常规成员函数.此处无法进行模板参数推导.

因此,当您编写 lamd 时,该变量会获得带有 operator()(int) 的闭包类型,而不是可使用 3 个整数调用的类型.>

如前所述,您可以改用通用 lambda.

在 C++20 中,如果您需要命名和推导 lambda 的参数类型,您可以使用以下语法:

auto lamd = [](Pack...) {}

将运算符定义为模板,接受参数包,并为模板参数推导敞开大门.

I was able to compile the following code with gcc:

template<typename... Pack>
auto func(Pack... x) {
    return (x + ...) ;
}

template<typename... Pack>
auto lamd = [](Pack... x) {
    return (x + ...) ;
};

I can invoke the function template with func(1,2,3), but I get an error when invoking a the lambda, with lamd(1,2,3) or lamd<int>(1,2,3).

解决方案

The second definition is a variable template. It does not define the lambda's operator() as a template, but rather takes the parameter pack for the argument types of operator(). The resulting operator() is a regular member function of the instantiated variable's closure type. There is no template argument deduction possible here.

So when you write lamd<int>, the variable gets a closure type with a operator()(int), not something callable with 3 integers.

As mentioned already, you can use a generic lambda instead.

In C++20, if you'd need the lambda's argument types to be named and deduced, you can use the syntax:

auto lamd = []<typename... Pack>(Pack...) {}

This will define the operator as template, accepting a parameter pack, and leave the door open for template argument deduction.

这篇关于如何调用 lambda 模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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