如何写一个通用的可变参数lambda,抛弃它的参数? [英] How to write a generic variadic lambda that discards its parameters?

查看:221
本文介绍了如何写一个通用的可变参数lambda,抛弃它的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个lambda,通过通用引用获取任意数量的参数,并完全忽略它们。显而易见的方法是使用可变参数通用参数包的语法,并省略参数名:

I want to write a lambda that takes an arbitrary number of arguments by universal reference and ignores them entirely. The obvious method would be to use the syntax for a variadic universal parameter pack and omit the parameter name:

auto my_lambda = [](auto&&...) { return 42; };

这很好(使用gcc 4.9.2),直到尝试传递非三维可复制对象

This works fine (with gcc 4.9.2) until I try to pass a non trivially-copyable object:

struct S { S() {} S(S const&) {} };
my_lambda("meow", 42, S{});
^ error: cannot pass objects of non-trivially-copyable type 'struct S' through '...'

发生了什么事?我的代码是不成形的,还是这是gcc中的一个错误?

What's going on? Is my code ill-formed, or is this a bug in gcc?

在这两种情况下,最好的解决方法是什么?我发现命名参数工程,但后来我遇到一个未使用的参数警告:

In either case, what's the best workaround? I found that naming the parameter works, but then I ran into an unused-parameter warning:

auto my_lambda = [](auto&&... unused) { return 42; };
^ error: unused parameter 'unused#0' [-Werror=unused-parameter]
^ error: unused parameter 'unused#1' [-Werror=unused-parameter]
^ error: unused parameter 'unused#2' [-Werror=unused-parameter]

模板参数包中未使用的参数警告?

How do you suppress an unused-parameter warning on a template parameter pack?

推荐答案

这是一个解析错误在GCC(你自己报告! auto&&&<... 在语法上不清楚,可以解析为 auto&&& $ c>或参数包声明(技术上,问题是 ... parameter-declaration-clause em> abstract-declarator );标准说它要解析为后者;

It's a parsing bug in GCC (which you yourself reported!). auto&&... is grammatically ambiguous and can be parsed as either the equivalent of auto&&, ... or a parameter pack declaration (technically, the question is whether ... is part of the parameter-declaration-clause or the abstract-declarator); the standard says it's to be parsed as the latter; GCC parses it as the former.

命名包解析解析歧义:

auto my_lambda = [](auto&&... unused) { return 42; };

要禁止警告,可以应用 __ attribute __((__ unused __))(或,如@Luc Danton建议, [[gnu :: unused]] ):

To suppress the warning, one could apply __attribute__((__unused__)) (or, as @Luc Danton suggested, [[gnu::unused]]):

auto my_lambda = [](auto&&... unused __attribute__((__unused__))) { return 42; };

或使用 sizeof ... p>

or use sizeof...

auto my_lambda = [](auto&&... unused) { (void) sizeof...(unused); return 42; };

这篇关于如何写一个通用的可变参数lambda,抛弃它的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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