Can you write a function using variadic templates that accepts an arbitrary list of tuples, each with a different set of parameters? So you would have something like:
template< /* some crazy variadic thing...*/ >
void func( ... ) {}
func(make_tuple(1,2), make_tuple("hello"));
SFINAE to the rescue!
Taking Jeffery's answer a little further, I wrote this little snippet. You can put types other than tuples anywhere in the argument list for func and it will compile and run, it will just break my printing chain when it hits the first type that isnt a template class. seq
and gens
come from here.
template<typename T>
int print(T& t) {
cout << t << " ";
return 0;
}
template<typename... T> void dumby(T...) {}
// so other template classes don't cause error (see bar below)
template<typename... A>
void expand(A... a) {}
template<typename... A, int... S>
void expand(tuple<A...> a, seq<S...>) {
dumby(print(get<S>(a))...);
cout << endl;
}
template<class... Types>
void func(Types...) {}
template<template<typename...> class A, class... Types, class... tup_types>
void func(A<tup_types...> a, Types... args) {
expand(a, typename gens<sizeof...(tup_types)>::type());
func(args...);
}
template<typename... A> struct bar {};
int main () {
func(make_tuple(0,1), make_tuple(2), 1, make_tuple("hello"), 0);
func(make_tuple(0,1), bar<int,int>(), make_tuple(2), 1, make_tuple("hello"), 0);
}
I'll have to find a practical use case to try it out but I'll call that a tentative success!
It's not possible. It could be possible to enforce that the type of the arguments is the same with a static_assert
or an std::enable_if
, but the unfortunate reality of std::tuple
is that it's a class template and can, therefore, generate multiple different types.
Your best shot is to make use of SFINAE. For example:
template<class A>
void func(A a) {
std::cout << "First of last: " << std::get<0>(a) << '\n';
}
template<class A, class... Types>
void func(A a, Types... args) {
std::cout << "First of element: " << std::get<0>(a) << '\n';
func(args...);
}
The above example will succeed when all the elements are tuples, but fail when they are not.