Variadic Templates
Feb 25, 2013 at 11:21am UTC
I'm looking for a way to enter an unlimited amount of types in the <> part of a template function, I found Variadic templates but I'm not sure if it can do it, all the examples I've found are similar to the C argument list and don't use the <> part of the template at all.
I tried this, but the overload is ambiguous, can anyone offer a solution?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include <iostream>
#include <typeinfo>
template <typename T>
void stuff()
{
std::cout << typeid (T).name() << "\n" ;
}
template <typename T, typename ... Args>
void stuff()
{
std::cout << typeid (T).name() << "\n" ;
stuff<Args...>();
}
int main()
{
stuff<int , float , double >();
return 0;
}
||=== Build: Debug in Variadic Templates Test (compiler: GNU GCC Compiler) ===|
Z:\Programming\C++\Projects\Variadic Templates Test\main.cpp||In instantiation of 'void stuff() [with T = float; Args = {double}]':|
Z:\Programming\C++\Projects\Variadic Templates Test\main.cpp|14|required from 'void stuff() [with T = int; Args = {float, double}]'|
Z:\Programming\C++\Projects\Variadic Templates Test\main.cpp|19|required from here|
Z:\Programming\C++\Projects\Variadic Templates Test\main.cpp|14|error: call of overloaded 'stuff()' is ambiguous|
Z:\Programming\C++\Projects\Variadic Templates Test\main.cpp|14|note: candidates are:|
Z:\Programming\C++\Projects\Variadic Templates Test\main.cpp|5|note: void stuff() [with T = double]|
Z:\Programming\C++\Projects\Variadic Templates Test\main.cpp|11|note: void stuff() [with T = double; Args = {}]|
||=== Build failed: 1 error(s), 3 warning(s) (0 minute(s), 0 second(s)) ===|
Feb 25, 2013 at 11:46am UTC
You can get rid of the ambiguity by letting the second stuff() take one extra template argument.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include <iostream>
#include <typeinfo>
template <typename T>
void stuff()
{
std::cout << typeid (T).name() << "\n" ;
}
template <typename T1, typename T2, typename ... Args>
void stuff()
{
std::cout << typeid (T1).name() << "\n" ;
stuff<T2, Args...>();
}
int main()
{
stuff<int , float , double >();
return 0;
}
Feb 25, 2013 at 11:56am UTC
Thanks :]
Topic archived. No new replies allowed.