“undefined reference” to static field template specialization

荒凉一梦 提交于 2020-01-03 16:01:39

问题


I have and header with a template class, which 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 only declared, because I intend to implement them with template specialization.

In a .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 functions that are implemented in the header and those that are only specialized in the .cpp. Note that Luaproxy<test>::CLASS_NAME and Luaproxy<test>::addfields seem to be found in linking.

What makes that map so special?


回答1:


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

The explicit constructor seem to convince gcc to effectively emit the variable. I asked #gcc for clarification, but unfortunately that channel is always silent.




回答2:


I built your code with just several extra semicolons and namespace tags in VC9, but there was neither compile error nor link error.

here are what I built:

Luaproxy.h file:

#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){}
};

Luaproxy.cpp file:

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


来源:https://stackoverflow.com/questions/8628314/undefined-reference-to-static-field-template-specialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!