I’m starting working with C++ templates just because I wanted to understand specific differences with other languages (Java) and I reached a point in which they started to diverge but I’m not getting how I am supposed to solve the specific problem (or get around it).
Suppose I have a generic value class, eg
template <class T>
class Value
{
protected:
T value;
public:
Value(Type type, T value) : type(type), value(value) {}
void set(T value) { this->value = value; }
T get() const { return this->value; }
T clone() { return new Value<T>(type, value); }
virtual string svalue() const = 0;
const Type type;
};
and a specific subtype:
class Int : public Value<int>
{
public:
Int(int value) : Value<int>(INT, value) { };
virtual string svalue() const { ... }
friend ostream& operator<<(ostream& os, const Int& v);
};
(I know it is also possible to specify type specific code by using template <> but since I still need to use it enough to understand it I just defined by own Int class for now, which is nothing more that a typedef Value<int> in the end)
Is it possible to have, let’s say, a collection that is able to store arbitrary pointers to Value instances? Without the need of specifying the specific concrete type of the generic class.
From what I understand templates are just a compile time issue for which the compiler analyzes all the concrete types for which the template is used and compiles different versions of the same methods for each of them, thus what I’m trying to do doesn’t seem to be possible (while in Java I am allowed to use wildcards for something like List<Value<?>>). Am I wrong?
Is there a common design to solve this issue or I am forced to drop templates to achieve it?
I think it’s pretty self-explanatory.