版权声明:本文为博主原创文章,欢迎转载。 https://blog.csdn.net/samylee/article/details/74458304
关于模板类:函数实现(.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)!