How to create an array of templated class objects?
Field<T1>
and Field<T2>
are two completely different types. To treat them in a vector you need to generialize then somewhere. You may write AbstractField
and
struct AbstractField{ virtual ~AbstractField() = 0;};template<class T,int fieldTypeId>class Field: public AbstractField{ private: T field; public: const static int field_type; public: virtual ~Field(){}};class Database_Record{ std::vector<AbstractField*> record; public: ~Database_Record(){ //delete all AbstractFields in vector }};
and then keep a vector
of AbstractField
. also use vector
instead of []
. Use AbstractField*
instead of AbstractField
and write at least one pure virtual in AbstractField
.
you may make the destructor of AbstractField
pure virtual. and don't forget to delete all AbstractField
s. in ~Database_Record()
You are going the wrong way.
Templates are used to create distinct types: std::vector<int>
and std::vector<float>
are distinct in much the same way (and as much) as int
and float
are.
Your syntax is also wrong; to create a dynamic array you'd put the following member in your Database_Record
:
std::vector<Field> record; // if this was possible; however, it's not
To put several objects of distinct type into a single array, they ought to have a common base class.
In order to create an array of different types you need a base class for the objects and the array will be an array of pointers to that base class. So, for example,
class Field{public: virtual ~Field() {} virtual std::string toString() const = 0; // and possibly other interface functions...};template <class T> FieldImpl : public Field{public: virtual std::string toString() const { std::stringstream ss; ss << val; return ss.str(); } // implementation of possibly other interface functions private: T val;}
will be the types you need. The array will then be something like
std::vector<std::unique_ptr<Field>> my_array;
You can then do stuff with your array using the interface functions, e. g.
my_array[i]->toString();