I created a container that controls the life cycle (new/delete) of certain types of objects to avoid any programming mistakes. For example, a object is deleted without any notification to the container. The objects inherit from the same base class (GreetingBase).
For the implementation I am using a "template trick":
class GreetingBase{
public:
virtual void sayHello(){
std::cout << "Hello there!" << endl;
}
virtual ~GreetingBase(){}
};
class GreetingDerived: public GreetingBase{
public:
virtual void sayHello(){
std::cout << "Hola amigos!" << endl;
}
virtual ~GreetingDerived(){}
};
class GreetingContainer{
public:
template <class T>
void addClass(){
items.push_back(new T());
}
~GreetingContainer(){
for(std::vector<GreetingBase*>::iterator it = items.begin();
it < items.end(); it++ ){
delete *it;
}
}
void talk(){
for(std::vector<GreetingBase*>::iterator it = items.begin();
it < items.end(); it++ ){
(*it)->sayHello();
}
}
private:
std::vector<GreetingBase*> items;
};
int main(){
GreetingContainer container;
container.addClass<GreetingDerived>();
container.talk();
return 0;
}
Questions:
- Using templates in order to solve this problem is a common approach? any drawbacks?
- Any "standard way" to report better errors messages when "T" is not derived from "GreetingBase"
Thank you in advance.