I have a finite number of classes with almost the same implementation, the only thing that is the main data type they manage:
class IntContainer { public: void setData(int data); int getData(); int _data; }; class BoolContainer { public: void setData(bool data); bool getData(); bool _data; }; class StringContainer { public: void setData(std::string data); std::string getData(); std::string _data; };
I would like to reduce code duplication of these classes using such patterns:
template<typename T> class GenericContainer { public: void setData(T data); T getData(); T _data; };
And specialization:
typedef GenericContainer<int> IntContainer; typedef GenericContainer<bool> BoolContainer; typedef GenericContainer<std::string> StringContainer;
It works well. But I would also like to add an abstract base class to these specialized classes in order to be able to manipulate them in a general way (for example, in a collection). The problem is that this base class must have getData and setData methods in order to be able to call them without even knowing the dynamic type of the object being processed.
I would execute it with something like this:
class Base { public: virtual void setData(??? data) = 0; virtual ??? getData() = 0; };
And use it something like this:
int main(int argc, char const *argv[]) { IntContainer intc = IntContainer(); intc.setData(42); std::cout << intc.getData() << std::endl; BoolContainer boolc = BoolContainer(); boolc.setData(false); std::cout << boolc.getData() << std::endl; std::vector<Base> v; v.push_back(intf); v.push_back(boolf); for (std::vector<Base>::iterator it = v.begin() ; it != v.end(); ++it) std::cout << it->getData() << std::endl; return 0; }
The problem is that I donโt know how to write prototypes of Base methods, since the type is unknown (and it doesnโt matter, the implementation of the derived class should be called at run time based on the dynamic type of the object).
TL DR: How to implement an abstract base class over several fully specialized templates?
Guillaume algis
source share