1
的代碼首先片段:派生類:使用基類成員在初始化列表
struct Base
{
int x{};
};
struct Derived :
Base
{
Derived()
: y{x}
{
}
int y;
};
int main()
{
Derived d;
}
上編譯罰款:
的代碼片段二:
#include <type_traits>
template<int N>
struct Base
{
int x = N;
};
static const int When0 = -1;
template<int N>
struct Derived :
std::conditional<N == 0,
Base<When0>,
Base<N>>::type
{
Derived()
: y{x}
{
}
int y;
};
int main()
{
Derived<0> d;
}
編譯精細:
不會編譯於:
要解決gcc和鐺,我需要指定x
的類:
#include <type_traits>
template<int N>
struct Base
{
int x = N;
};
static const int When0 = -1;
template<int N>
struct Derived :
std::conditional<N == 0,
Base<When0>,
Base<N>>::type
{
using base_t = typename std::conditional<N == 0,
Base<When0>,
Base<N>>::type;
Derived()
: y{base_t::x}
{
}
int y;
};
int main()
{
Derived<0> d;
}
見(VC編譯會太):
問題:哪個編譯器是正確的?什麼標準說這個?
由於
在Visual Studio中禁用「語言擴展」('/ Za')使其拒絕您的第二個片段。經常使用的經驗法則:如果有疑問,VC++是錯誤的。 – molbdnilo
@molbdnilo,謝謝 – grisha