我有一个模板类头文件,它只有静态函数和字段.
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
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的那样,只会声明一些函数,因为我打算用模板特化来实现它们.
在.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...
}
Run Code Online (Sandbox Code Playgroud)
我Luaproxy<test>::fields从头文件中实现的函数和仅专门用于.cpp的函数中获取未定义的引用错误.请注意,Luaproxy<test>::CLASS_NAME并Luaproxy<test>::addfields似乎在联系被发现.
是什么让map这么特别?
我知道 C++ 模板函数的定义必须放在头文件中。然而,出于提高我正在制作的(可能)大型库的可读性和结构的原因,我将声明与实现分开,放入“模拟”标头(其中#include实现文件,非常类似于这种文件结构)。请注意,我是否知道模板化函数的实现必须在编译时包含在内,并且我正在这样做。
简而言之,当我将非模板化函数声明添加到实现文件中时,出现“多重定义”错误。下面是带有示例的长解释。
\n\n当“模拟”头文件+实现文件对仅包含模板化函数的声明/实现对时,一切正常。当我仅在实现文件中添加新模板化函数的实现时,它也可以正常工作。
\n\n工作示例(当我想使用此功能时我会这样做)#include "algo.h":main.cpp
“模拟”头文件 algo.h :
\n\n#ifndef ALGO_H\n#define ALGO_H\n\nnamespace fl{\n template <typename Compare>\n void algo(.. non-templated args .., Compare order = std::less<int>());\n}\n\n#include "tpp/algo.cpp"\n\n#endif // ALGO_H\nRun Code Online (Sandbox Code Playgroud)\n\n实现文件 tpp/algo.cpp : (目前只是algo.tpp )
\n注意:使用该tpp/.cpp文件是在初始版本中,现在我使用每个@\xcf\x80\xce\xac\xce\xbd\xcf 的.tpp文件\x84\xce\xb1 \xe1\xbf\xa5\xce\xb5\xe1\xbf\x96 \的建议,解释在最后。
#ifndef TPP_ALGO\n#define TPP_ALGO\n\n#include "../algo.h"\n\nnamespace fl{\n\n template <typename Compare>\n …Run Code Online (Sandbox Code Playgroud)