如何在 C++ 中合并来自两个参数包的值? 也就是说,函数怎么写
LetsStart<int, -1, 10, 3>("This is -1", "And this is 10", "3!!!");
输出结果
-1 This is -1
10 And this is 10
3 3!!!
即它应该从第一个包中选择第一个值,从第二个包中选择第一个值,然后从两个包中选择第二个值,然后从两个包中选择第三个值,依此类推...
在我的第一次尝试中,我尝试了这样的事情
template<class T, T... Firsts, class TSecond>
void LetsStart(TSecond... Seconds) {
Output((Firsts, Seconds)...);
}
但这没有用...
//当然是我wrote this function ,但我相信存在更正确和更简单的方法来完成此任务。那么,你能给我指路吗?
最佳答案
在C++11中,可以使用如下函数:
template<typename T, T... V, typename F, typename... A>
void f(F &&f, A&&... args) {
static_assert(sizeof...(V) == sizeof...(A), "Argument lists size mismatch");
int arr[] = { 0, (std::forward<F>(f)(V, std::forward<A>(args)), 0)... };
(void)arr;
}
它接受请求的两个参数列表和一个额外的函数 F
,然后它解压缩参数并将每个列表的 N-th 传递给给定函数。
它也应该在没有提供参数的情况下工作。
在C++17中你可以重写如下:
template<typename T, T... V, typename F, typename... A>
void f(F &&f, A&&... args) {
static_assert(sizeof...(V) == sizeof...(A));
(std::forward<F>(f)(V, std::forward<A>(args)), ...);
}
在这两种情况下,我都检查了两个列表是否具有相同的大小,因为没有指定在这种情况下该怎么做。
您可以使用下面的示例 main
测试这两个函数:
#include<utility>
#include<iostream>
// ...
int main() {
auto l = [](auto v, auto s) { std::cout << v << " " << s << std::endl; };
f<int, -1, 10, 3>(l, "This is -1", "And this is 10", "3!!!");
}
关于c++组合来自两个(或更多)参数包的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26078946/