简体   繁体   中英

How to access params in variadic template function

The old way to make variadic function in C/C++ is using va_list, va_start, va_arg, va_end defined in cstdarg. C++11 comes with variadic function template syntax, but how to access the values?

//example
#include <iostream>
using namespace std;

template <typename... types>
void print(types... Params){
  //this is not working:
  long Param1 = Params[0];
  long Param2 = Params[1];
}

int main(){
  print(123, 456);
  print(123, "foobar");
}

This a very simple (not disruptive) way to do it, although perhaps not optimal:

#include <iostream>
#include<tuple>
#include<cassert>

using namespace std;

template <typename... types>
void print(types... Params){
  long Param1 = std::get<0>(std::tie(Params...));
  long Param2 = std::get<1>(std::tie(Params...));
  assert(Param1 == 123 and Param2 == 456);
}
int main(){
  print(123, 456);
}

https://godbolt.org/z/V8VA0W

If all elements are of the same type (and assuming you can copy them):

#include <iostream>
#include<tuple>
#include<cassert>

using namespace std;

template <typename... types>
void print(types... Params){
  std::array<long, sizeof...(Params)> params = {Params...};
  long Size = params.size();
  long Param1 = params[0];
  long Param2 = params[1];
  assert(Size == 2 and Param1 == 123 and Param2 == 456);
}

int main(){
  print(123, 456);
}

It is not clear from your question but it looks like you want to print all the elements in the list, if you just want to do this then you can do it as follows (needs C++17, but you can do this with some work in c++11):

#include <iostream>

using namespace std;

template <typename... types>
void print(types... Params){
    std::cout << "number of elements: " << sizeof...(Params) << " ";
    ((std::cout << Params), ...);
}

int main(){
  print(123, 456);
}

There's a solution using operator<< here: https://stackoverflow.com/a/5495309/5581893

But it's not actually a single function call, it's a series of calls to operator<<, and the function can't be in global scope, it must be a method in a type.

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