我遇到了一个问题,我正在尝试解决我想要一些抽象基类的问题,它继承自多个类,其中派生可以选择覆盖它们的方法,而无需声明额外的类。我将在这里举例说明我要实现的目标:
#include <iostream>
using namespace std;
class A
{
public:
virtual void foo() = 0;
protected:
A() {}
};
class A1 : public A
{
public:
A1() : A() {}
void foo() { cout << "A1 foo" << endl; };
};
class A2 : public A
{
public:
A2() : A() {}
void foo() { cout << "A2 foo" << endl; };
};
class B
{
public:
virtual void bar() { cout << "B bar: " << endl; }
};
class B1 : public B
{
public:
void bar()
{
cout << "B1 bar wrapper begin" << endl;
B::bar();
cout << "B1 bar wrapper end" << endl;
}
};
/*
???
pure virtual class C
enforce derived classes to inherit something of type A
enforce derived classes to inherit something of type B
class C1 : public A1, either B or B1 ??? templates???
{
}
class C2 : public A2, either B or B1 ??? templates???
{
}
Can this be done without having to define classes CA1B, CA2B, CA1B1, CA2B1, etc.?
*/
int main(int argc, char *argv[])
{
A1 a1;
a1.foo();
A2 a2;
a2.foo();
/*
C1 c1b with type B
C1 c1b1 with type B1
C2 c2b with type B
C2 c2b1 with type B1
put c1b, c1b1, c2b, c2b1 in a list named "combinations"
cout << "Printing combinations" << endl;
for (auto i : combinations)
{
i->foo();
i->bar();
}
*/
return 0;
}
理论上输出是:
A1 foo
A2 foo
Printing combinations
A1 foo
B bar
A1 foo
B1 bar wrapper begin
B bar
B1 bar wrapper end
A2 foo
B bar
A2 foo
B1 bar wrapper begin
B bar
B1 bar wrapper end
如果有一种方法可以通过某种设计模式来实现这一点,或者我使用的方法不好,请告诉我。我正在使用 C++11。
最佳答案
您的用例尖叫着“带有约束的模板”。您缺少的是如何检查和编码模板参数是否继承自正确的类。你可以用 std::is_base_of
做到这一点
template<class A_, class B_,
typename std::enable_if<std::is_base_of<A, A_>::value>, int>::type = 0,
typename std::enable_if<std::is_base_of<B, B_>::value>, int>::type = 0>
class C : public A_, public B_
{
};
这是它的工作原理:
std::enable_if
会有一个 type
(在我们的例子中是 int
),当且仅当输入的 bool 表达式为真。否则那里没有类型,模板将无法编译。如果那里有类型,那么我们就获得了一个非类型模板参数,我们给它默认值0
。到。分配默认值使我们能够使用两个参数实例化模板。
您会在 <type_traits>
中找到这些实用程序以及更多内容标题。
关于c++ - 需要关于多重继承和可选函数覆盖 C++ 的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46324825/