I want to have a class that holds a data member whose type can vary. Something like:
struct container
{
void push( auto x );
private:
auto m_x;
};
Where the type isn't known until I call push()
. How would I do this?
I want to have a class that holds a data member whose type can vary. Something like:
struct container
{
void push( auto x );
private:
auto m_x;
};
Where the type isn't known until I call push()
. How would I do this?
template<typename T>
struct container
{
void push(T x);
private:
T m_x;
};
You could try boost::any
, which lets you store any type but the later retrieval and use must be aware of the actual type (it may try a specific type, work through a list of potential types...).
If you may need to store any type but later during retrieval only need to perform certain operations on the value (for example, streaming the value to a std::ostream
, adding it to another such value, ...), you can capture those operations as pointers to function template instantiations, or by instantiating a class template in which the operations are overrides of base class methods, such that your container can store a pointer to the base class and dispatch using runtime polymorphism.
In C++, it's not possible to implement a class that holds a data member whose type can vary.
Depending on your exact needs, the following solutions come close:
Both solutions fall short in one way or the other; it depends on the exact problem which one is better suited.