C++ 在Visual Studio中通过派生模板静态成员使用基础模板静态成员
考虑以下代码:C++ 在Visual Studio中通过派生模板静态成员使用基础模板静态成员,c++,visual-studio,templates,static,initialization,C++,Visual Studio,Templates,Static,Initialization,考虑以下代码: #include <iostream> template <typename T> struct A { T x; A(T X) : x(X) { } static const A a; }; template <typename T> const A<T> A<T>::a(5); template <typename T> struct B : public A<T&
#include <iostream>
template <typename T> struct A
{
T x;
A(T X) : x(X) { }
static const A a;
};
template <typename T> const A<T> A<T>::a(5);
template <typename T> struct B : public A<T>
{
B(T X) : A<T>(X) { }
static const B b;
};
template <typename T> const B<T> B<T>::b(A<T>::a.x);
int main()
{
//auto test0 = A<int>::a.x;
auto test1 = B<int>::a.x;
auto test2 = B<int>::b.x;
auto test3 = A<int>::a.x;
std::cout << "test1 = " << test1 << "\ttest2 = " << test2 <<
"\ttest3 = " << test3 << std::endl;
return 0;
}
但在2015年之前的任何VisualStudio上运行时都不会。VS生产:
test1 = 5 test2 = 0 test3 = 5
除非在main()中取消注释test0变量的定义。为什么?
看起来MSVC++不会初始化基本模板结构静态成员,除非在使用派生结构之前显式实例化它。这可能与动态常量初始化有关,但我不确定这里到底发生了什么
如何克服这种行为?每次我都需要B::B.x
等于B::a.x
,而不必强迫自己先实例化a
。
粗鄙的诡计是可以接受的。谢谢。克服此问题的最简单方法是升级编译器。
test1 = 5 test2 = 0 test3 = 5