外部模板 c++ 的问题

Issue with extern templates c++

本文关键字:问题 c++ 外部      更新时间:2023-10-16

我正在使用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>;

我希望你会发现它有帮助,科雷尔。