参考https://blog.csdn.net/mincheat/article/details/77987740
一般情况,模板函数被外部其他引用会提示找不到函数,原因是:
编译本身这个cpp的时候,没有发现有引用的地方,那么就不会被编译,而编译引用这个模板函数的其他cpp的时候,要直接调用这个函数,就会发现这个函数没有编译,没有实现,所以报错,找不到该函数。
解决方法:在cpp文件中进行显示指定类型的模板实例化。
适用场景:希望对外声明提供的头文件简单并隐藏实现。
动态库VS2017demo:
templateTest.h:
#pragma once
#include <iostream>
using namespace std;
#ifdef TEST_EXPORT_API
#define TEST_API __declspec(dllexport)
#else
#define TEST_API __declspec(dllimport)
#pragma comment(lib, "templateTest.lib")
#endif
class TEST_API templateTest
{
public:
template<class T>
void publicFunc(T arg)
{
cout << "publicFunc" << arg << endl;
}
template<class... T>
void privateFunc(const T&... args);
void test();
};
templateTest.cpp:
#include "templateTest.h"
// <类型>(参数修饰):<T>(const T&)、<T>(const T)、<T>(const T*)
template void TEST_API templateTest::privateFunc<int>(const int&);
// 显示实例化可变参数中无参数的情况:
template void TEST_API templateTest::privateFunc<>();
template<class... T>
void templateTest::privateFunc(const T& ...args)
{
cout << "privateFunc" << endl;
}
void templateTest::test()
{
privateFunc(5);
}
main.cpp:
#include <iostream>
#include "templateTest.h"
using namespace std;
int main()
{
templateTest temp;
temp.privateFunc(5);
getchar();
}
以上是在msvc中使用动态库中的模板函数中的方法。在gcc中更简单了,只需要:
#define TEST_API
在windows中使用动态库,如果不用__declspec(dllexport)导出 __declspec(dllimport)导入,则模板函数会提示找不到