在以下代碼中,編譯器正在請求基類類X爲默認構造爲。但是,如果我從類節點後,進入該成員m_x變,當然,曖昧的繼承刪除虛擬關鍵字,但類X的默認構造函數不再需要。虛擬繼承是否強制基類成爲默認可構造的?
這是什麼原因?
#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;
}
這幾乎是一個*最小*的例子。我可以從這裏刪除約100行代碼! – Barry
@抱歉抱歉,但我認爲保持示例有效的唯一多餘的事情是基類C.我希望代碼清晰,即使它比最小值長一點。 – nyarlathotep108
只要'A','X'和'Node'就足夠了(不需要'Apply','Inheritance','B','C'或'Example' ......) –
Barry