In a design of a class hierarchy, I’m using an abstract base class that declares various methods that the derived classes would implement. In a sense, the base class is as close to an interface as you can get in C++. However, there is an specific issue. Consider the code below which declares our interface class:
class Interface {
public:
virtual Interface method() = 0;
};
class Implementation : public Interface {
public:
virtual Implementation method() { /* ... */ }
};
Of course, this wouldn’t compile, because you cannot return an abstract class in C++. To get around this problem I’m using the following solution:
template <class T>
class Interface {
public:
virtual T method() = 0;
};
class Implementation : public Interface<Implementation> {
public:
virtual Implementation method() { /* ... */ }
};
This solution works and is all fine and dandy, however, to me, it doesn’t look very elegant, because of the redundant bit of text which would be the parameter for interface. I’d be happy if you guys could point our any other technical issues with this design, but that is my only concern at this point.
Is there any way to get rid of that redundant template parameter? Possibly using macros?
Note: The method in question has to return an instance. I’m aware that if method() returned a pointer or a reference, there would be no issue.
Interface::method()cannot return anInterfaceinstance without using a pointer or reference. Returning a non-pointer, non-referenceInterfaceinstance requires instantiating an instance ofInterfaceitself, which is illegal becauseInterfaceis abstract. If you want the base class to return an object instance, you have to use one of the following:A pointer:
A reference:
A template parameter: