我正在研究一個靜態庫,並且該庫有多個類模板和函數模板。我明白爲了使用靜態庫內的模板,所有的東西(聲明/定義)都需要在頭文件中。然而,在這種特殊的情況下,因爲我知道我認爲我可以用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