Template Partial Static Field Initialization Specialization

I am trying to do something like the following:

struct MyType { }; template <typename T> struct Test { static const MyType * const sm_object; }; template <> struct Test<void> { static const MyType * const sm_object; }; template <typename T> const MyType * const Test<T>::sm_object = new MyType(); template <> const MyType * const Test<void>::sm_object = new MyType(); 

I include this in 2 files - a.cpp and b.cpp. I am trying to compile and get:

 error C2998: 'const MyType *Test<void>::sm_object' : cannot be a template definition 

I assume that my C ++ syntax is bad, but I can't think what I'm doing wrong.

I can’t remove template<> from the variable definition, since I need it in several translation units, and this will lead to a link error.

I can put the field in the base class and use CRTP to create a new instance for each type, and then specialization will not interfere, but why does this β€œdirect” field initialization not work? I need to skip some piece of syntax.

I am using VS2003 :(

+4
source share
3 answers

Judging by g ++, I think you need to remove template<> from this line and put the remainder in one source file (not in the header). Since this is a specialization, this is just an ordinary static template that you do not define in the header.

In some .C file:

const MyType * const Test<void>::sm_object = new MyType();

+6
source

I believe you want to do something like this

 struct MyType { }; template <typename T> struct Test { static const MyType * const sm_object; static const MyType* set_object() { return nullptr; } }; template <> struct Test<void> { static const MyType * const sm_object; static const MyType* set_object() { return new MyType(); } }; template <typename T> const MyType * Test<T>::sm_object = Test< T >::set_object(); 
+2
source

I believe the following code may be of some interest to some people:

 #include <stdio.h> template<class X,int Y> struct B { X content; static const int nr=Y; }; int main(int, char**) { B<char,1> a; B<int,2> b; B<int,3> c; printf("%d, %d, %d\n",a.nr,b.nr,c.nr); } 
0
source

Source: https://habr.com/ru/post/1334360/


All Articles