Derived class: 在初始化列表中使用 Base class 成员
Derived class: using Base class member in initializer list
第一段代码:
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 和 clang,我需要指定 x
的 class:
#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也会编译):
问题:哪个编译器是正确的?什么标准对此有何规定?
谢谢
这是从模板派生 class 访问基 class(非依赖)成员的标准问题。参见 this FAQ entry。
简单地改成this->x
也可以,所以VC++这里是错误的。
第一段代码:
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 和 clang,我需要指定 x
的 class:
#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也会编译):
问题:哪个编译器是正确的?什么标准对此有何规定?
谢谢
这是从模板派生 class 访问基 class(非依赖)成员的标准问题。参见 this FAQ entry。
简单地改成this->x
也可以,所以VC++这里是错误的。