外部模板 c++ 的问题
Issue with extern templates c++
我正在使用C++,但我在外部模板方面遇到了困难。与 C# 相反,整个模板实现在C++ :(中真的很讨厌
template_test.hpp
template<class T>
class CFoo {
public:
T Foo_Func(const T& test);
};
template_test.cpp
#include "Template_Test.hpp"
template<class T>
T CFoo<T>::Foo_Func(const T& test)
{
return test;
}
template_test2.hpp
#include "Template_Test.hpp"
extern template class CFoo<int>;
int Template_Tests();
template_test2.cpp
#include "Template_Test2.hpp"
int Template_Tests()
{
CFoo<int> foo_instance;
//this causes an undefined reference
int res = foo_instance.Foo_Func(1);
return res;
}
为什么链接器找不到我的函数。我认为外部模板的工作方式与外部变量相同。 (将extern int test;
放在头文件中,int test = 0
放在源文件中。
感谢您的支持:(
解决方案 1
解决此问题的一种方法是在没有函数定义的情况下实现模板类的函数。 在这种情况下:
template<class T>
class CFoo {
public:
T Foo_Func(const T& test) {
return test;
}
};
然后,您甚至不需要extern
部分。我知道你的程序员意识一直告诉你要避免这种情况,并且总是在你的类函数的定义和它们的实现之间分开 - 但在 c++ 的模板情况下,这是这种语言巨大问题的最简单的解决方案。
您需要知道的一件重要事情 - 不同 IDE 之间的此问题解决方案之间存在很大差异,但这种简单的解决方案适用于大多数(如果并非总是如此(。
解决方案 2
另一种选择,如果您仍然想将实现与定义分开,您可以包含.cpp文件以及 .hpp/.h 文件:
template_test2.hpp
#include "Template_Test.hpp"
#include "Template_Test.cpp"
/*extern template class CFoo<int>;*/ // Again, you don't need this extern
int Template_Tests();
解决方案 3
这是最接近您尝试的方式。 在文件的末尾template_test.cpp
添加以下行:
template class CFoo<int>;
并从template_test2.hpp
文件中删除行extern template class CFoo<int>;
。
我希望你会发现它有帮助,科雷尔。
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题