2011-12-25 55 views
4

我有一个模板类,它只有静态函数和字段的头。“未定义的参考”静态字段模板专业化

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 
} 

正如你所看到的一些函数只是声明的,因为我打算用模板专门化来实现它们。

在.ccp文件我有:

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... 
} 

我从只专业的.cpp是在头实现的函数和那些得到了一个未定义引用错误Luaproxy<test>::fields。请注意,Luaproxy<test>::CLASS_NAMELuaproxy<test>::addfields似乎可以在链接中找到。

是什么让map如此特别?

+0

使“模板类Luap​​roxy <>;”输入你的cpp文件的顶部。我认为那必须解决它 – Arunmu

回答

5

我终于设法得到它的工作,但我coul真的不知道为什么我的编译器(gcc 4.6.1)需要这种方式:template<> std::map<std::string, fieldproxy> Luaproxy<test>::fields=std::map<std::string, fieldproxy>();

显式构造函数似乎说服gcc有效地发出变量。我问了#gcc澄清,但不幸的是,这个频道总是沉默。

2

我用VC9中的几个额外的分号和名称空间标记构建了您的代码,但没有编译错误和链接错误。

这里是什么我建:

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

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文件:

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

你的代码不适合我,这很奇怪。我的编译器是gcc 4.6.1。偶然的,我添加了一个显式的构造函数声明到字段,现在编译。在3个小时内,我将能够自我回答并更深入地解释这一点。 –