خرید بک لینک

Vote count: 0

Consider following code:

#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;

    retu 0;
}

Ruing this code may give the following text:

test1 = 5    test2 = 5    test3 = 5

But not when ruing on any Visual Studio up to 2015. VS produces:

test1 = 5    test2 = 0    test3 = 5

unless you uncomment definition of test0 variable in main(). Why?

Looks like MSVC++ doesn't initialize base template struct static member, unless you explicitly instantiate it before using derived struct. This is probably related to dynamic constant initialization, but I'm not sure what's really happening here.

How to overcome this behavior? I need B::b.x to be equal to B::a.x everytime, without forcing myself to remember to instantiate A first. Hackish trickeries are acceptable. Thanks.

asked 2 mins ago

برچسب: نویسنده: استخدام کار تاريخ: سه شنبه 18 خرداد 1395 ساعت: 9:05

صفحه بندی