我正在研究一个静态库,并且该库有多个类模板和函数模板。我明白为了使用静态库内的模板,所有的东西(声明/定义)都需要在头文件中。然而,在这种特殊的情况下,因为我知道我认为我可以用forward的专业化类型来代替专业化。具有模板实例化的模板静态库
这个技巧与类模板(及其功能)很好地结合,我可以使用我的应用程序代码中的所有库函数。然而,当我介绍免费函数模板库中,我尝试使用免费的模板功能从我的应用程序代码,它给了我链接错误:
error LNK2019: unresolved external symbol "class TemplatedStaticLib __cdecl HelpingRegistration(int)" ([email protected]@@[email protected]@@[email protected]) referenced in function _main 1>C:\src\cpp\vs2008\StaticLibExample\MathFuncsLib\Debug\TemplatedStaticLibApp.exe : fatal error LNK1120: 1 unresolved externals" I am using VS2008, here is the code
//静态库的头文件(.h)中
#ifndef _TEMPLATED_STATIC_LIB_
#define _TEMPLATED_STATIC_LIB_
#include <iostream>
template<typename T>
class TemplatedStaticLib
{
public:
TemplatedStaticLib(){};
~TemplatedStaticLib(){};
void print(T t);
};
template<typename T>
TemplatedStaticLib<T> HelpingRegistration(T);
#endif
//静态库类文件(的.cpp)
#include "TemplatedStaticLib.h"
//Specialization
template class TemplatedStaticLib<double>;
template class TemplatedStaticLib<int>;
template class TemplatedStaticLib<std::string>;
template<typename T>
void TemplatedStaticLib<T>::print(T t)
{
std::cout << "Templated Print " << typeid(t).name() << std::endl;
}
void HelpingRegistration(void)
{
}
//Specialization of free function
template<> TemplatedStaticLib<int> HelpingRegistration<int>(int);
template<> TemplatedStaticLib<double> HelpingRegistration<double>(double);
template<> TemplatedStaticLib<std::string> HelpingRegistration<std::string>(std::string);
template<typename T>
TemplatedStaticLib<T> HelpingRegistration(T t)
{
std::cout << "Function Templated Print " << typeid(t).name() << std::endl;
return t;
}
//应用程序代码
#include "TemplatedStaticLib.h"
int main(int argc, char* argv[])
{
int anInt = 99;
TemplatedStaticLib<int> test;
test.print(anInt);//works
double aDouble = 3.9;
TemplatedStaticLib<double> double_test;
double_test.print(aDouble); //works
std::string aString = "James";
TemplatedStaticLib<std::string> string_test;
string_test.print(aString);//works
//The following lines gives linker error
HelpingRegistration(anInt);
HelpingRegistration(aDouble);
HelpingRegistration(aString);
return 0;
}
我不知道为什么它是不同的,我如何解决这个问题。任何帮助表示赞赏。
无法在翻译单元中定义模板。 – 0x499602D2 2013-02-26 01:12:47
模板滥用的经典示例 – 2013-02-26 01:20:01
嗯,我想知道为什么它适用于类模板的情况呢? – jazaman 2013-02-26 01:24:35