简体   繁体   中英

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. Note that this is C++14, but there are plenty of implementations around for C++11 if needs be.

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 :

template<typename ... Tn>
int GetArgValues(std::vector<std::string> keys, Tn&... values){
  //Check sizes
  //...

  return GetArgValuesHelp(std::index_sequence_for<Tn...>{}, keys, values...);
}

Live Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM