假设我们有以下接口
// 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
。如何做到这一点?我尝试了多重继承,但没有成功。
您的意思可能是这样吗?
#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();
}