Reputation: 35982
Given the following prototype, is it possible to implement it in C++? I am looking for resources(books, web) that can give me some concrete ideas to implement it in C++.
class Container
{
public:
vector<Element> getElementsByCategory(Category _cate);
bool AddElement(Element _element);
bool DelElement(Element _element);
private:
vector<Element> vec;
};
struct Element
{
Category cate;
DataType type;
DataValue value;
};
Category can be CategoryA, CategroyB, CategoryC, etc.
DataType can be Date, int, float, double, string, etc.
DateValue is correspoding to DataType.
As you can see, the class Container
can hold dynamic element each of different data type. The user is responsible for adding each different field(column in DB) to the Container
and later Container
provides way to return categorized data back to the user.
For example, the user can add Element of int type, Element of double type, and Element of Date type into container at the very beginning. Then later, the user would like to query all elements that belong to int type.
Upvotes: 2
Views: 182
Reputation: 23868
One way this can be done is to have a common base class for all of you classes. Store a pointer to this base class in the vector. Dont forget to iterate through the vector and free everything at destruction time.
struct Base {};
class Category : public Base {};
class DataType : public Base {};
class DataValue : public Base {};
std::vector<Base *> data;
data.push_back(new Categroy);
data.push_back(new DataType);
data.push_back(new DataValue);
Upvotes: 0
Reputation: 26930
I don't know if this is what you want, but it seems to me that you need a :
template<class Category, class DataType>
struct Element : public ElementBase //so that your container can hold the items
Category cate;
DataType type;
DataType value;
};
It goes without saying that your vector should be : Vector<ElementBase*> vec;
Upvotes: 1