一种模板类实现和声明分开在生成的.a文件被使用时出现undefined reference时的一种解决方法
模板类头文件格式如下:
test.h
// test.h
namespace test {
namespace _testspace {
class base {
public:
base();
~base();
};
template<bool T>
class base_impl : public base {
public:
base_impl() {
}
void func1();
void func2();
};
} //namespace _test
typedef _testspace::base_impl<false> ft;
typedef _testspace::base_impl<true> tt;
}//namespace test
test.cpp如下:
#include "test.h"
namespace test {
namespace _testspace {
base::base() {
}
base::~base() {
}
void base_impl::func1() {
}
void base_impl::func2() {
}
}
template class _testspace::base_impl<false>;
template class _testspace::base_impl<true>;
}
尤为重要的是cpp中的最后两行代码,如果缺少,在使用的时候必报undefined reference
文章讲述了在C++中,如何处理当模板类的实现和声明分开时,由于缺少模板实例化而在使用时出现undefinedreference的编译错误。提供了解决方案,强调了在cpp文件中正确实例化模板类的重要性。

被折叠的 条评论
为什么被折叠?



