Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在Visual Studio中通过派生模板静态成员使用基础模板静态成员_C++_Visual Studio_Templates_Static_Initialization - Fatal编程技术网

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