模板的声明和定义分别在两个文件中,其中function.h内容为
#ifndef _BC_FUNCTION_H_
#define _BC_FUNCTION_H_
template<typename T>
T add(const T &a,const T &b);
template<typename T>
T mul(const T& a,const T& b);
template<typename T>
T div(const T& a,const T& b);
template<typename T>
T sub(const T& a,const T& b);
#include "../src/function.cpp"
#endif
function.cpp内容为
#ifndef _FUNCTION_CPP_
#define _FUNCTION_CPP_
#include "../include/function.h"
template<typename T>
T add(const T &a,const T &b)
{
return a+b;
}
template<typename T>
T mul(const T &a,const T &b)
{
return a*b;
}
template<typename T>
T div(const T& a,const T &b)
{
return a/b;
}
template<typename T>
T sub(const T &a,const T& b)
{
return a-b;
}
#endif
如果定义类并且类中有static变量需要在类外初始化为
template <typename T>
T* Foo<T>::shared_resource_ = nullptr;