My goal is to implement a container (here a set of stacks, one for each type) that accepts many different types of objects simultaneously. This would be trivial to do at runtime, using void pointers (or a common base class for all stored types) and runtime type indentification (RTTI). Since all types the container is going to hold are known at compile time, it may (or may not) be possible to make such a class using templates. I am aware that boost::variant
already provides similar functionality, but it requires that the stored types are listed as template arguments, as in boost::variant< int, std::string > v;
.
What I'm really looking for is a class that transparently adds a matching (internal) data strucure to itself each time a new template specialization of the equivalent of push()
is created. The usage of the class would look like this:
int main()
{
MultiTypeStack foo;
//add a double to the container (in this case, a stack). The class would
//..create a matching std::stack<double>, and push the value to the top.
foo.push<double>(0.1);
//add an int to the container. In this case, the argument type is deduced.
//..The class would create a std::stack<int>, and push the value to the top.
foo.push(123);
//push a second double to the internal std::stack<double>.
foo.push<double>(3.14159);
std::cout << "int: " << foo.top<int>() << "\n"; //"int: 123"
std::cout << "double: " << foo.top<double>() << "\n";//"double: 3.14159"
return 0;
}
A naïve implementation as an example:
template<typename T> struct TypeIndex;
template<> struct TypeIndex<int>{enum{i = 0};};
template<> struct TypeIndex<double>{enum{i = 1};};
class MultiTypeStack
{
public:
template<typename T>
void push(const T &val){std::get<TypeIndex<T>::i>(stacks_).push(val);}
template<typename T>
void pop(){std::get<TypeIndex<T>::i>(stacks_).pop();}
template<typename T>
T top(){return std::get<TypeIndex<T>::i>(stacks_).top();}
private:
std::tuple<std::stack<int>, std::stack<double>> stacks_;
};