模板类:函数实现(.cpp)和函数声明(.h)分开的问题

关于模板类:函数实现(.cpp)和函数声明(.h)分开的问题已经是个老问题了,一般不能分开编写,否则编译出错,原因不多说。

但是caffe编写的声明和实现分开了,而且还不冲突,原因就是使用了类模板实例化了。

举个栗子(以下代码可以通过测试):

 

类函数声明test.h

 

//类模板实例化的问题
//作者:samylee
#ifndef TEST_H
#define	TEST_H

#include <string>
#include <iostream>
#define INSTANTIATE_CLASS(classname) template classname<std::string> //实例化模板(string类型)

namespace lee {

	template <typename Dtype>
	class Test
	{
	public:

		void hello(Dtype str);
		void print();

	private:
		Dtype newstr;
	};
}

#endif // !TEST_H

 

 

 

 

 

函数实现test.cpp

 

//类模板实例化的问题
//作者:samylee
#include "test.h"

namespace lee {

	template<typename Dtype>
	void Test<Dtype>::hello(Dtype str)
	{
		newstr = str;
	}

	template<typename Dtype>
	void Test<Dtype>::print()
	{
		std::cout << newstr << std::endl;
	}

	INSTANTIATE_CLASS(Test);//实例化Test
}

 

 

 

 

 

主函数main.cpp

 

//类模板实例化的问题
//作者:samylee
#include "test.h"

int main()
{
	lee::Test<std::string> test;
	test.hello("hello world");
	test.print();
	system("pause");
}

 

 

 

 

任何问题请加唯一QQ2258205918(名称samylee)!

唯一VX:samylee_csdn

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值