Generic base class with multiple template specialized derived classes

abstract-class, c++, inheritance, templates

Solution

There is simply no way to do what you want.

The problem is, if this was allowed, the compiler would have to generate as many virtual methods in the base class as there are possible specializations of the template child class (ie. an infinity) which is not possible.

Problem

I have a finite amount of classes with the nearly-same implementation, the only different being the underlying type of data they manipulate: ``` 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; }; // Etc. You get the idea. ``` I'd like to reduce the code duplication of these classes by using templates like so: ``` 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; ``` This works well. But I'd also like to add an abstract base class to these specialized classes to be able to manipulate them in a generic way (eg. in a collection). The problem is this base class should have the `getData` and `setData` methods to be able to call them even without knowing the dynamic type of the object manipulated. I would implement it with something like this: ``` class Base { public: virtual void setData(??? data) = 0; virtual ??? getData() = 0; }; // Modify GenericContainer's definition like so template<typename T> class GenericContainer : Base { ... } ``` And use it somehow like that: ``` 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 I don't know how to write the `Base` methods prototypes as the type is unknow (and does not matter, the derived class implementation should be called at runtime based on the dynamic type of the object). TL;DR: How to implement an abstract base class over several fully specialized templated classes ?

Original source