我知道从 Args...args 到像这样的数组相对容易:
template<typename...Args>
void f(Args...args){
double list[] = {args...};
}
但是,有没有办法返回到 Args,例如:
template<typename...Args>
void f(Args...args){
double list[] = {args...};
//manipulate list[]
//convert list to new_args...
//use it in a function
any_other_f(new_args...);
}
最佳答案
永不言败。由于您似乎知道 list
的大小 (=sizeof...(args)
),您可以使用 c++14 库功能试试运气,并且创建一个 index_sequence
,然后在解包期间使用它来索引列表。看这里:http://en.cppreference.com/w/cpp/utility/integer_sequence .底部的示例显示了如何执行此操作。
我的第一次尝试:
#include <iostream>
#include <utility>
using namespace std;
template<typename... Args>
void any_other_f(Args... args)
{
double list[] = {args...};
for (auto&& x : list)
cout << x << ", ";
cout << "\n";
}
template<typename T, size_t... I>
void wrapper_function(T&& t, index_sequence<I...>)
{
any_other_f(t[I]...);
}
template<typename...Args>
void f(Args...args)
{
constexpr size_t size = sizeof...(args);
double list[] = {args...};
for (int i = 0; i < size; ++i)
list[i] *= -1;
wrapper_function(list, make_index_sequence<size>());
}
int main()
{
f(1.0, 2.0, 3.0);
}
它有效:http://ideone.com/OmfOps .
唯一的要求是你需要知道你想在编译时解压的东西的大小。或者至少您需要进行猜测,然后在运行时崩溃。
关于c++ - 为可变参数打包数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27908708/