Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

c++ - How to create an array of templated class objects?

I haven't done any C++ programming for quite some time and I decided that I would mess around with it a little bit in my spare time so I decided to write me a little database program just for fun and I'm having trouble with creating an array of templated class objects.

What I have is this class which I want to use to represent a field in a database record.

template <class T, int fieldTypeId>
class Field
{
private:
    T field;
    int field_type;
public:
    // ...
};

And I want to use an array of that class to represent a record in a database using this class.

class Database_Record
{
private:
    int id;
    Field record[];
public:
    Database_Record(int);
    Database_Record(int, Field[]);
   ~Database_Record();
};

Where I'm stuck at is the creation of the array in the Database_Record class since that is an array of templated class objects with each element possibly being of a different type and I'm not sure how I need declare the array because of that. Is what I'm trying to do even possible or am I going about it the wrong way? Any help would be greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 AbstractFields. in ~Database_Record()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...