"undefined reference" to static field template specification

I have a header with a template class that has only static functions and fields.

template<typename T> class Luaproxy { static std::map<std::string, fieldproxy> fields; static const char * const CLASS_NAME; static void addfields(); static int __newindex(lua_State * l){ //implemented stuff, references to fields... } //etc } 

As you can see, some of the functions are declared only because I intend to implement them using specialized specialization.

In the .ccp file, I have:

 struct test { int a; } template<> map<string, fieldproxy> Luaproxy<test>::fields; template<> const char * const Luaproxy<test>::CLASS_NAME=typeid(test).name(); template<> void Luaproxy<test>::addfields(){ //stuff, references to fields... } 

I get undefined reference errors to Luaproxy<test>::fields from both the functions that are implemented in the header and those that specialize only in .cpp. Note that Luaproxy<test>::CLASS_NAME and Luaproxy<test>::addfields seem to be in the link.

What makes this map so special?

+4
source share
2 answers

I finally managed to get it working, but I could not say why my compiler (gcc 4.6.1) needs it like this: template<> std::map<std::string, fieldproxy> Luaproxy<test>::fields=std::map<std::string, fieldproxy>();

The explicit constructor seems to convince gcc to efficiently emit the variable. I asked #gcc to clarify, but unfortunately this channel was always silent.

+5
source

I built your code with a few extra semicolons and namespace tags in VC9, but there was no compilation error or link error.

here is what i built:

File Luaproxy.h:

 #pragma once #include <map> #include <string> typedef int fieldproxy; struct lua_State; struct test { int a; }; template<typename T> class Luaproxy { public: static std::map<std::string, fieldproxy> fields; static const char * const CLASS_NAME; static void addfields(); static int __newindex(lua_State * l){} }; 

File Luaproxy.cpp:

 #include "Luaproxy.h" template<> std::map<std::string, fieldproxy> Luaproxy<test>::fields; template<> const char * const Luaproxy<test>::CLASS_NAME=typeid(test).name(); template<> void Luaproxy<test>::addfields(){} 

main.cpp file:

 #include "Luaproxy.h" int _tmain(int argc, _TCHAR* argv[]) { Luaproxy<test> *p = new Luaproxy<test>; p->fields["foo"] = 0; delete p; return 0; } 
+2
source

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


All Articles