I am interrested in interface implementation. I know the standard way of doing so is to code a class having pure virtual methods which is going to be used as interface, for instance:
class Interface {
public:
virtual void doSometing() = 0;
}
and to have it used:
class Implementation : public Interface {
public:
virtual void doSomething() override { ... }
}
Or even better to apply NVI (non virtual interface).
But all those use virtual functions which I am trying to avoid - as I am coding for embedded where performance loss due to vtable indirections must be considered.
Threfore I focused onto 'static polymorphism' and try to use CRTP to implement the interfaces:
template<typename T>
class Interface {
public:
void doSomething() {
static_cast<T&>(*this)._doSomething();
}
class Implementation : public Interface<Implementation> {
public:
void _doSomething() { /* Do implementation specific stuff here */ }
}
class Implmentation2 : public Interface<Implementation2> {...}
So far so good. But there is one big trouble I see. Once I want to store a bunch of pointers to the interface to some container and want to access the instances of various implementation classes I face the trouble the Interface<T>
is allways a different class by itself, not a single interface:
Interface<Implementation>
and Interface<Implementation2>
are different types.
Ok, let's make a common base class to derive the interfaces from...
template<typename T>
class Interface : public IfaceBase {
public:
void doSomething() {
static_cast<T&>(*this)._doSomething();
}
...but then I cannot access the final instance using the interface. It seems to me I am trying to create interface to interface which sounds crazy by itself anyway...
So I found CRTP not too usable in this case. I have searched the internet and have found MIXIN which seems to be a "CRTP turned upside down". But I am not sure whether it can be used for my purpose...
Could you please help me? If there is a way how to apply MIXINS or any other idiom/whatever to have C++ interfaces without virtuals, please share the idea :)
Many thanks in advance to anybody willing to help! Cheers Martin