如何实现一个接口并同时继承另一个专用模板

问题描述 投票:0回答:1

假设我们有以下接口

// 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>
{
}

然后在实施中

// 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;
    }
}

现在我想实现

SpecInterface
并继承
MyServiceImpl::fun1
。如何做到这一点?
在UML中:

我尝试了多重继承,但没有成功。

c++ inheritance pure-virtual
1个回答
0
投票

您的意思可能是这样吗?

#include <iostream>

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

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

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();
}
© www.soinside.com 2019 - 2024. All rights reserved.