In my project, I have a base abstract class with an interface, which derived classes implement. These derived classes have generic functions that accept parameters of different types. I have written these generic functions in my derived classes using function templates.
I want to add these templated functions to the interface in my base class. So I can achieve polymorphism: accept base class in other functions and call these templated functions in derived classes.
When we have normal functions, we do virtual and override, but you can't do virtual with templated functions.
I tried to do pure abstract templated functions in my abstract base class but it doesn't work.
Here's a small program with the functionality I'm trying to achieve, which doesn't compile because of virtual <template...
:
#include <vector>
class ObjectTransformerBaseAbstractClass {
public:
virtual template<typename TStructure> TStructure ToStructure(std::vector<unsigned char> bytes) = 0;
virtual template<typename TStructure> std::vector<unsigned char> ToBytes(TStructure structure) = 0;
};
class ObjectTransformer1 : public ObjectTransformerBaseAbstractClass {
template <typename TStructure> TStructure ToStructure(std::vector<unsigned char> bytes) {
// some implementation
}
template <typename TStructure> std::vector<unsigned char> ToBytes(TStructure structure) {
// some implementation
}
};
class ObjectTransformer2 : public ObjectTransformerBaseAbstractClass {
template <typename TStructure> TStructure ToStructure(std::vector<unsigned char> bytes) {
// some other implementation
}
template <typename TStructure>
std::vector<unsigned char> ToBytes(TStructure structure) {
// some other implementation
}
};
template <typename TStructure>
void coutStructureBytes(ObjectTransformerBaseAbstractClass *objectTransformerBaseAbstractClass, TStructure structure) {
// transform structure to bytes using the passed objectTransformerBaseAbstractClass object and cout it.
}
In my base class I need to say "Implement these pure abstract generic functions which accept different parameters of different types and do stuff in derived classes". And in my derived classes I need to implement these pure abstract generic functions that accept parameters of different types.
I don't understand how to achieve this functionality I want to have(which you can see in the above program, if it compiled and worked). Please, recommend a solution or explain how to make this work.