Im folgenden Code fordert der Compiler die Basis Klasse X als default construcible an. Allerdings, wenn ich entfernen Sie das virtuelle Schlüsselwort aus dem Erbe der Klasse Node, den Zugangs zum Mitglied m_x wird, natürlich, nicht eindeutig, aber die Standardkonstruktors für Klasse X ist nicht mehr erforderlich .Erzwingt die virtuelle Vererbung, dass eine Basisklasse standardmäßig konstruierbar ist?
Was ist der Grund dafür?
#include <iostream>
struct Apply
{
template< typename T >
struct Node : virtual T // this line contains the virtual inheritance
{
template< typename ...Args>
Node(Args... args)
: T(args...)
{}
};
template < typename ...BaseClasses>
struct Inheritance;
template < typename FirstBaseClass, typename ...OtherBaseClasses>
struct Inheritance< FirstBaseClass, OtherBaseClasses... > : FirstBaseClass
, Inheritance<OtherBaseClasses...>
{
template< typename ...Args>
Inheritance(Args... args)
: FirstBaseClass(args...)
, Inheritance<OtherBaseClasses...>(args...)
{
}
};
};
template < >
struct Apply::Inheritance< >
{
template< typename ...Args>
Inheritance(Args... args){}
};
struct X
{
X(int i){}
int m_x;
};
struct A : Apply::Node<X>
{
A(int i)
: Apply::Node<X>(i)
, m_a(i)
{
}
int m_a;
};
struct B : Apply::Node<X>
{
B(int i)
: Apply::Node<X>(i)
, m_b(i)
{ }
int m_b;
};
struct C : Apply::Node<X>
{
C(int i)
: Apply::Node<X>(i)
, m_c(i)
{ }
int m_c;
};
struct Example : Apply::Inheritance< A, B, C >
{
Example(int i)
: Apply::Inheritance< A, B, C >(i)
{ }
void print() const
{
// this line needs the virtual inheritance
std::cout << m_x << std::endl;
std::cout << m_a << std::endl;
std::cout << m_b << std::endl;
std::cout << m_c << std::endl;
}
};
int main()
{
Example ex(10);
ex.print();
return 0;
}
Dies ist kaum ein * minimal * Beispiel. Ich kann ungefähr 100 Zeilen Code von hier ausschneiden! – Barry
@Barry sorry dafür, aber ich denke, das einzige überflüssige Ding, um das Beispiel gültig zu halten, ist die Basisklasse C. Ich hoffe, der Code ist klar, auch wenn es ein bisschen länger als das Minimum ist. – nyarlathotep108
Nur 'A',' X' und 'Knoten' ist ausreichend (brauchen nicht 'Apply',' Vererbung', 'B',' C', oder 'Beispiel' ...) –
Barry