So I've been trying to understand variadic templates a little bit more, My goal was to receive all types, expand them, and print them.. I was able to do it in for a function(found some examples) but I was not able to do it for a class Here I am trying to build a 'Master' to hold many 'Slaves', each Slave is supposed to have a Slave_T inherit from him and then know it's type, and print it on c'tor.
But for some reason I am not able to fix the ambigious compilation error.. I was trying to avoid passing any of the type as parameters to the function.. I tried with enable_if or true/false_type convensions but was unable, anyone has any idea? This is my code:(function expansion included)
Function expansion that works:
template<typename T, typename... Targs> void Print(T value, Targs... Fargs) // recursive variadic function { Print<T>(); Print(Fargs...); // recursive call } template<typename T> void Print(T = NULL) { std::cout << typeid(T).name() << endl; } Class Expansion that I need help with:
#include <iostream> #include <vector> #include <type_traits> #include <memory> using namespace std; struct Slave { virtual char const* Type() = 0; }; template<typename T> struct Slave_T : public Slave{ virtual char const* Type() { return typeid(T).name(); } }; template <typename ...T> struct Master { Master() { MakeSlave<T...>(); cout << "All Slaves:" << endl; for (auto const& slave : v){ cout << slave ->Type() << endl; } } private: template<typename T, typename ...Rest> void MakeSlave() { MakeSlave<Rest...>(); MakeSlave<T>(); } template<typename T> void MakeSlave() { v.push_back(new Slave_T<T>()); } vector<shared_ptr<Slave>> v; }; int main() { Master<int, double, char> m; //Print("Hello", '!', 123, 123); return 0; } Thanks!
Alon