How to implement an interface and inherit from another specialized template at the same time

96 Views Asked by At

Let's say we have following interfaces

// interface

template <typename T>
class MyInterface
{
public:
    virtual void fun1() = 0;
    virtual void fun2() = 0;
}

// just specialization, keep pure virtual
class SpecInterface: public MyInterface<int>
{
}

Then in implementation

// interface_impl

template <typename T>
class MyServiceImpl : public MyInterface<T>
{
    virtual void fun1() override {
        std::cout << "concrete MyService f1" << std::endl;
    }
    
    // keep fun2 unimplemented
}

class SpecInterfaceImpl : public SpecInterface
{
    // I want the MyServiceImpl::fun1 here

    virtual void fun2() override {
        std::cout << "concrete SpecService f2" << std::endl;
    }
}

Now I want to implement the SpecInterface and also inherit from MyServiceImpl::fun1. How to do that?
In UML: enter image description here

I tried multiple inheritance but without luck.

1

There are 1 best solutions below

0
Pepijn Kramer On

Do you perhaps mean something like this?

#include <iostream>

// interfaces
class interface1_t
{
public:
    virtual ~interface1_t() = default;
    virtual void method1() = 0;
};

class interface2_t
{
public:
    virtual ~interface2_t() = default;
    virtual void method2() = 0;
};

// mixin classes for interface implementations
template <typename base_t>
class interface1_impl : public interface1_t
{
public:
    void method1() override
    {
        std::cout << "method1\n";
    }
};

template <typename base_t>
class interface2_impl : public interface2_t
{
public:
    void method2() override
    {
        std::cout << "method2\n";
    }
};

// this class will implement both interfaces
// by mixin in both implementations.
// this pattern will never lead to diamond inheritance
class my_class_t :
    public interface1_impl<my_class_t>,
    public interface2_impl<my_class_t>
{
};


int main()
{
    my_class_t my_class;
    my_class.method1();
    my_class.method2();
}