c++ - 外部模板c ++的问题
问题描述
我正在使用 C++,我在使用外部模板时遇到了困难。与 C# 相反,整个模板实现在 C++ 中真的很讨厌 :(
模板测试.hpp
template<class T>
class CFoo {
public:
T Foo_Func(const T& test);
};
模板测试.cpp
#include "Template_Test.hpp"
template<class T>
T CFoo<T>::Foo_Func(const T& test)
{
return test;
}
模板测试2.hpp
#include "Template_Test.hpp"
extern template class CFoo<int>;
int Template_Tests();
模板测试2.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 模板的工作原理与 extern 变量相同。(放入extern int test;
头文件和int test = 0
源文件。)
谢谢你的支持:)
解决方案
解决方案 1
解决这个问题的一种方法是在没有函数定义的情况下实现模板类的函数。在这种情况下:
template<class T>
class CFoo {
public:
T Foo_Func(const T& test) {
return test;
}
};
然后,你甚至不需要这个extern
部分。我知道你的程序员一直在告诉你要避免这种情况,并且总是将你的类函数的定义和它们的实现分开——但在 c++ 中的模板案例中,这是解决这种语言巨大问题的最简单的解决方案。
您需要知道的一件重要事情 - 不同 IDE 之间针对此问题的解决方案存在很大差异,但这种简单的解决方案适用于大多数 IDE(如果并非总是如此)。
解决方案 2
另一种选择,如果您仍想将实现与定义分开,您可以包含 .cpp 文件以及 .hpp/.h 文件:
模板测试2.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>;
extern template class CFoo<int>;
并从template_test2.hpp
文件中删除该行。
我希望你会发现它有帮助,科雷尔。
推荐阅读
- node.js - 使用 Node 和 OAuth2/OpenID 连接的 websocket 的身份验证/授权
- python - 用作表达式的子查询返回的 Django ORM 多于一行
- python - Python:BERT Tokenizer 无法加载
- javascript - 如何将 @HostListener('window:beforeunload', ['$event']) 实现到 canDeactivate 保护指令中?
- python - 如何从 json 中提取数据并使用 python 为提取的值添加附加值?
- javascript - 打开新窗口后,Material UI Tooltip 出现在停靠面板中
- firebase - 持久的 Google Cloud Anchors Android - 无密钥身份验证中缺少 apikey
- xml - 如果 p 子元素出现在子元素之前关闭并在包含子字符元素的子元素之后使用 xslt 打开
- javascript - 制作一个计算字符串中数字的函数
- ios - 如何在应用程序 SwiftUI 中从任何地方显示警报?