[英]Unpacking Parameter Pack in C++
I have two functions f
and g
. 我有两个函数f
和g
。 f
calculates it's return value asynchronously and returns a future. f
异步计算它的返回值并返回一个未来。 Now, based on several return values of f
, I want to call g
, but I want to make sure that the computations of the values of f
happen in parallel. 现在,根据f
几个返回值,我想调用g
,但我想确保f
值的计算并行发生。
Consider the following code: 请考虑以下代码:
template <typename T>
std::future<T> f(T& t);
template <typename... T>
void g(T&&... t)
template <typename... T>
void call_wrapper(T&&... t) {
auto f1 = f(t1); // How do I set the values of f1... fn
auto f2 = f(t2);
...
g(f1.get(), f2.get()....); // How do I call g
}
How can I unpack the types from the variadic template T
of the call_wrapper
function? 如何从call_wrapper
函数的可变参数模板T
中解压缩类型?
[Edit2: I guess i misunderstood the question, i forgot subzero wanted to return std::future
s and simply thought that the only problem was the parameter pack syntax. [编辑2:我想我误解了这个问题,我忘了subzero想要返回std::future
s并且只是认为唯一的问题是参数包语法。 Hopefully, using an helper function as in my first edit should work though] 希望在我的第一次编辑中使用辅助函数应该可以工作]
You can simply do: 你可以简单地做:
template <typename... T> void call_wrapper(T&&... t) { g(f(std::forward<T>(t)).get()...); }
Unless i misunderstood what you want to do. 除非我误解了你想做什么。
Edit1: if you want to do something else, you can divide the function in two calls, like this: Edit1:如果你想做其他事情,可以在两次调用中划分函数,如下所示:
template<typename... T>
void helper(T&&... t) {
// ...
g(std::forward<T>(t).get()...);
}
template <typename... T>
void call_wrapper(T&&... t) {
helper(f(std::forward<T>(t))...);
}
Here's a quick solution storing the std::future
s in a std::tuple
: 这是一个快速解决方案,将std::future
存储在std::tuple
:
template <class T, std::size_t... Idx>
void callG(T &tuple, std::index_sequence<Idx...>) {
g(std::get<Idx>(tuple).get()...);
}
template <typename... T>
void call_wrapper(T&&... t) {
auto results = std::make_tuple(f(std::forward<T>(t))...);
callG(results, std::index_sequence_for<T...>{});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.