I experimented using template recursion to create nested POD structures, and I came across some kind of behavior that I did not expect. Here's a simplified example:
#include <cstddef> template<std::size_t size> struct RecursiveStruct { public: template <std::size_t start, std::size_t length> struct Builder { static const Builder value; static const size_t mid = start + length / 2; static const size_t end = start + length; Builder<start, mid - start> left; Builder<mid, end - mid> right; }; template <std::size_t start> struct Builder<start, 1> { static const Builder value; int data; }; static const Builder<0, size> result; }; template<std::size_t size> const typename RecursiveStruct<size>::template Builder<0, size> RecursiveStruct<size>::result = Builder<0, size>::value; template<std::size_t size> template<std::size_t start, std::size_t length> const typename RecursiveStruct<size>::template Builder<start, length> RecursiveStruct<size>::Builder<start, length>::value = { Builder<start, mid - start>::value, Builder<mid, end - mid>::value }; template<std::size_t size> template <std::size_t start> const typename RecursiveStruct<size>::template Builder<start, 1> RecursiveStruct<size>::Builder<start, 1>::value = { 5 }; //////////////////////////////////////////////////////// #include <iostream> using std::cout; using std::endl; using std::size_t; int main() { cout << RecursiveStruct<1>::result.data << endl; cout << RecursiveStruct<2>::result.left.data << endl; return 0; }
I expect this code to output
5 5
In fact, this is what is generated when compiling with GCC 4.8.4 and 5.1.
However, compiling with Clang (3.5 or 3.7) or Visual Studio 2010 produces results
5 0
Is my code or my understanding of it incorrect in any way, or does Clang and Visual Studio somehow have errors that lead to the same erroneous result?
c ++ initialization templates
rkjnsn
source share