虚拟继承和默认构造函数
Virtual inheritance and default constructor
这是一个示例代码:
#include <iostream>
#include <utility>
using namespace std;
struct D;
struct X {};
struct Y {};
template <typename T>
struct A // A : ASequencialPlanningJobQueueFactory
{
A() = delete;
A(T* t) { cout << "A constructor" << endl; }
};
struct B : A<B> // B : AThermostatedRotorJobQueueFactory
{
B(B* b, const X& x, const Y& y) : A(b) { cout << "B constructor" << endl; }
};
template <typename T>
struct C : T // C : PlanningJobQueueFactoryStub
{
template <typename... Args>
C(Args&&... args) : T(std::forward<Args>(args)...) { cout << "C constructor" << endl; }
};
struct D : C<B> // D: ThermostatedRotorJobQueueFactoryStub
{
D(const X& x, const Y& y) : C(this, x, y) { cout << "D constructor" << endl; }
};
int main()
{
X x;
Y y;
D d(x, y);
cout << "----------" << endl;
return 0;
}
如果我向 B 添加虚拟继承,如:
struct B : virtual A<B>
{
B(B* b, const X& x, const Y& y) : A(b) { cout << "B constructor" << endl; }
};
代码不再编译。为什么?
找了好久才发现错误。
Clang 和 gcc 不是很有帮助...
使用虚拟继承,最派生的 class 应该调用虚拟基构造函数,所以:
struct D : C<B> // D: ThermostatedRotorJobQueueFactoryStub
{
D(const X& x, const Y& y) : A(this), C(this, x, y) { cout << "D constructor" << endl; }
};
但是C<B>
也是如此:
template <>
struct C<B> : B
{
template <typename... Args>
C(Args&&... args) : A(this), B(std::forward<Args>(args)...) {
cout << "C constructor" << endl;
}
};
这是一个示例代码:
#include <iostream>
#include <utility>
using namespace std;
struct D;
struct X {};
struct Y {};
template <typename T>
struct A // A : ASequencialPlanningJobQueueFactory
{
A() = delete;
A(T* t) { cout << "A constructor" << endl; }
};
struct B : A<B> // B : AThermostatedRotorJobQueueFactory
{
B(B* b, const X& x, const Y& y) : A(b) { cout << "B constructor" << endl; }
};
template <typename T>
struct C : T // C : PlanningJobQueueFactoryStub
{
template <typename... Args>
C(Args&&... args) : T(std::forward<Args>(args)...) { cout << "C constructor" << endl; }
};
struct D : C<B> // D: ThermostatedRotorJobQueueFactoryStub
{
D(const X& x, const Y& y) : C(this, x, y) { cout << "D constructor" << endl; }
};
int main()
{
X x;
Y y;
D d(x, y);
cout << "----------" << endl;
return 0;
}
如果我向 B 添加虚拟继承,如:
struct B : virtual A<B>
{
B(B* b, const X& x, const Y& y) : A(b) { cout << "B constructor" << endl; }
};
代码不再编译。为什么?
找了好久才发现错误。 Clang 和 gcc 不是很有帮助...
使用虚拟继承,最派生的 class 应该调用虚拟基构造函数,所以:
struct D : C<B> // D: ThermostatedRotorJobQueueFactoryStub
{
D(const X& x, const Y& y) : A(this), C(this, x, y) { cout << "D constructor" << endl; }
};
但是C<B>
也是如此:
template <>
struct C<B> : B
{
template <typename... Args>
C(Args&&... args) : A(this), B(std::forward<Args>(args)...) {
cout << "C constructor" << endl;
}
};