Here's a minimal example:
#include <iostream> struct B { B() { x = 42; } static int x; }; int B::x; template <int N> struct A { int foo() { return bx; } static B b; }; template<int N> B A<N>::b; //template struct A<2>; // explicit instantiation with N = 2 (!) int main(int argc, char **argv) { std::cout << A<1>().foo() << std::endl; return 0; }
This program writes 42 using g ++ 4.9.2, but writes 0 using Visual Studio 2015 RC. Also, if I uncomment the explicit instantiation, VS2015RC also gives 42, which is quite interesting, since the template parameter here is different from the one used in the main function.
This is mistake? I assume g ++ is correct, since there is a link to b inside foo , so the constructor of b should be called.
EDIT: There is a simple workaround - if in b there is a non-static variable referenced in A , VS2015RC will compile correctly:
// ... struct B { B() { x = 42; } static int x; int y; // <- non-static variable }; // ... template <int N> struct A { int foo() { by; return bx; } // <- reference to by static B b; };
This seems to work, although by , as a statement, is obviously NOP.
source share