c++将模板实现放在cpp,外部使用模板的方法(demo,gcc+msvc(动态库))

参考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)导入,则模板函数会提示找不到

  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值