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);
}
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);
}