I want to instantiate a variadic template class Store<TArgs...> that has a std::vector for each type in the TArgs... pack.
template<typename... TArgs> class Store {
// obviously not valid code
// assuming each type of TArgs... has a `unsigned int` id that can be
// retrieved with getId<T>()
std::array<sizeof...(TArgs), std::vector<TArgs...>> bags;
template<typename T> void add(T mValue) {
bags[getId<T>()].push_back(mValue);
}
template<typename T> std::vector<T>& get() {
return bags[getId<T>()];
}
};
Let's say I have a Store<int, float, double>. I obviously know, at compile time, that it will be able to store int, float and double values.
I could use template specializations:
template<> class Store<int, float, double> {
std::vector<int> vi;
std::vector<float> vf;
std::vector<double> vd;
template<typename T> void add(T);
template<> void add<int>(int mValue) { vi.push_back(mValue); }
template<> void add<float>(float mValue) { vf.push_back(mValue); }
template<> void add<double>(double mValue) { vd.push_back(mValue); }
// ...
};
...but that would require hand-writing every possible combination of types, and would not work with user-defined types.
I'm confident the compiler knows everything that's required to generate a class like Store<int, float, double> using variadic templates - is there a way to actually express this intent?
std::tupleto do this,std::vectorisn't suitable. - πάντα ῥεῖstd::array<sizeof...(TArgs), std::vector<TArgs...>>, the order of template arguments is wrong. It should bestd::array<Type, Size>, notstd::array<Size, Type>. Also, I think you needstd::tuple, notstd::vector(I'm not sure though). - Nawaz