[英]variadic template arguments unpacking
For each argument I need apply two nested function: 对于每个参数,我需要应用两个嵌套函数:
obj.apply(someFilter(arg)); // arg is one argument, but here
// should be an unpacking of args
I don't know how to write unpacking for such case. 我不知道如何为这种情况写解包。
I saw this: 我看到了这个:
pass{([&]{ std::cout << args << std::endl; }(), 1)...};
on wiki , but again don't know how to apply this for my case. 在维基上 ,但又不知道如何应用于我的情况。
It's actually quite simple: You can put arbitrary expression inside the unpack of an variadic templates argument pack: 它实际上非常简单:您可以将任意表达式放在variadic模板参数包的解包中:
obj.apply(someFilter(arg))...
This will give you the result of obj.apply
as a coma seperated list. 这将为您提供
obj.apply
作为昏迷分隔列表的结果。 You can then pass it to a dummy function: 然后,您可以将其传递给虚拟函数:
template<typename... Args> swallow (Args&&...) {}
swallow(obj.apply(someFilter(arg))...);
To swallow the comma seperated list. 吞下逗号分隔列表。
Of course, this assumes that obj.apply
returns some kind of object. 当然,这假设
obj.apply
返回某种对象。 If not you can use 如果没有,你可以使用
swallow((obj.apply(someFilter(arg)), 0)...);
to make actual (non void
) arguments 制作实际(非
void
)参数
If you don't know what obj.apply` returns (result might have overloaded the comma operator), you can disable the use of custom comma operators by using 如果你不知道obj.apply`返回什么(结果可能重载了逗号运算符),你可以通过使用禁用自定义逗号运算符的使用
swallow((obj.apply(someFilter(arg)), void(), 0)...);
Should you actually need to evaluate the items in order (which doesn't seem very likely from the question), you can abuse array initialization syntax instead of using a function call: 如果您确实需要按顺序评估项目(这似乎不太可能来自问题),您可以滥用数组初始化语法而不是使用函数调用:
using Alias=char[];
Alias{ (apply(someFilter(args)), void(), '\0')... };
I assume that the code has multiple arg
s as a parameter pack? 我假设代码有多个
arg
作为参数包? Try: 尝试:
obj.apply( someFilter( arg )... );
as parameter unpacking applies to the expression, so each element of the parameter pack get's expanded into someFilter( arg )
. 因为参数解包应用于表达式,所以参数包的每个元素都被扩展为
someFilter( arg )
。
Here is a robust way to do an arbitrary set of actions on a parameter pack. 这是一种在参数包上执行任意操作集的可靠方法。 It follows the principle of least surprise, and does the operations in order:
它遵循最少惊喜的原则,并按顺序执行操作:
template<typename Lambda, typename Lambdas>
void do_in_order( Lambda&& lambda, Lambdas&& lambdas )
{
std::forward<Lambda>(lambda)();
do_in_order( std::forward<Lambdas>(lambdas)... );
}
void do_in_order() {}
template<typename Args>
void test( Args&& args ) {
do_in_order( [&](){obj.apply(someFilter(std::forward<Args>(args)));}... );
}
Basically, you send a pile of lambdas at do_in_order
, which evaluates them front to back. 基本上,你在
do_in_order
发送一堆lambdas,它从前到后评估它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.