[英]How to expand vectors or arrays in variadic parameter pack?
I would like to expand an array or a vector in a variadic template pack. 我想在可变参数模板包中扩展数组或向量。 Consider the following example: 考虑以下示例:
template <typename T>
int GetArgValue(std::string name,T& value){
cout<<"GetArgumentValue(): name="<<name<<", val="<<value<<endl;
//Set value
//...
return 0;
}
template<typename ... Tn>
int GetArgValues(std::vector<std::string> keys, Tn&... values){
//Check sizes
//...
//Call GetArg over pack
int retCodes[] = { GetArgValue(keys,values)...};//not possible
//...
return 0;
}
Is it possible to expand arrays or vectors together with the pack? 是否可以与包一起扩展数组或向量? If not what would be a suitable approach for this use case? 如果不是,哪种方法适合该用例? What I would like to achieve at the end is the following: 最后,我想实现以下目标:
double arg1;
int arg2;
std::string arg3;
GetArgValues({"firstArg","secondArg","thirdArg"},arg1,arg2,arg3);
or even better (if possible): 甚至更好(如果可能):
GetArgValues( {"firstArg",arg1}, {"secondArg",arg2}, {"thirdArg", arg3} );
Hope that the example is clear. 希望例子清楚。 Thanks all for suggestions. 谢谢大家的建议。
You could use std::index_sequence
for this. 您可以为此使用std::index_sequence
。 Note that this is C++14, but there are plenty of implementations around for C++11 if needs be. 请注意,这是C ++ 14,但是如果需要,C ++ 11周围有很多实现。
We make a helper function which will receive a compile-time-generated sequence of indices to access the vector with: 我们创建一个辅助函数,该函数将接收编译时生成的索引序列,以使用以下方式访问向量:
template<typename ... Tn, std::size_t... Idx>
int GetArgValuesHelp(std::index_sequence<Idx...>,
std::vector<std::string> keys,
Tn&... values){
int retCodes[] = { GetArgValue(keys[Idx],values)...};
return 0;
}
Then call that function and generate the indices from GetArgValues
: 然后调用该函数并从GetArgValues
生成索引:
template<typename ... Tn>
int GetArgValues(std::vector<std::string> keys, Tn&... values){
//Check sizes
//...
return GetArgValuesHelp(std::index_sequence_for<Tn...>{}, keys, values...);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.