可变参数模板参数解包 [英] variadic template arguments unpacking

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

问题描述

对于每个参数,我需要应用两个嵌套函数:

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.

我看到了:

 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:

obj.apply(someFilter(arg))...

这会给你 obj.apply 的结果作为一个昏迷分隔列表.然后你可以将它传递给一个虚拟函数:

This will give you the result of obj.apply as a coma seperated list. You can then pass it to a dummy function:

template<typename... Args> swallow (Args&&...) {}
swallow(obj.apply(someFilter(arg))...);

吞下逗号分隔的列表.

当然,这假设 obj.apply 返回某种对象.如果没有,您可以使用

Of course, this assumes that obj.apply returns some kind of object. If not you can use

swallow((obj.apply(someFilter(arg)), 0)...);

制作实际(非void)参数

如果您不知道 obj.apply` 返回什么(结果可能使逗号运算符重载),您可以使用以下方法禁用自定义逗号运算符

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

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')... };

这篇关于可变参数模板参数解包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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