C++ 如何在可变参数包中扩展向量或数组?
我想展开可变模板包中的数组或向量。 考虑下面的例子:C++ 如何在可变参数包中扩展向量或数组?,c++,variadic-templates,C++,Variadic Templates,我想展开可变模板包中的数组或向量。 考虑下面的例子: template <typename T> int GetArgValue(std::string name,T& value){ cout<<"GetArgumentValue(): name="<<name<<", val="<<value<<endl; //Set value //...
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;
}
或者更好(如果可能):
希望这个例子是清楚的。
谢谢大家的建议。您可以使用
std::index\u sequence
。注意,这是C++14,但是如果需要的话,C++11有很多实现
我们制作了一个助手函数,该函数将接收编译时生成的索引序列,以访问向量:
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;
}
#1
{“firstArg”,arg1}
不是推断类型,std::make_pair(“firstArg”,arg1)
将是一个选项。(另一种选择是:GetArgValues(“firstArg”,arg1,“secondArg”,arg2,“thirdArg”,arg3);
)作为最后一种选择。是否将字符串转换为类型化参数?@Galik:无需转换字符串。字符串参数在内部用作键,用于从列表中查找参数对象。
GetArgValues( {"firstArg",arg1}, {"secondArg",arg2}, {"thirdArg", arg3} );
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;
}
template<typename ... Tn>
int GetArgValues(std::vector<std::string> keys, Tn&... values){
//Check sizes
//...
return GetArgValuesHelp(std::index_sequence_for<Tn...>{}, keys, values...);
}