我使用的是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
放在源文件中。)
感谢您的支持:)
发布于 2018-05-30 07:20:42
解决方案1
解决这个问题的一种方法是在没有函数定义的情况下实现模板类的函数。在这种情况下:
template<class T>
class CFoo {
public:
T Foo_Func(const T& test) {
return test;
}
};
然后,您甚至不需要extern
部分。我知道您的程序员意识一直在告诉您要避免这种情况,并且总是将类函数的定义和它们的实现分开-但是在c++中的模板情况下,对于这种语言的巨大问题,这是最简单的解决方案。
你需要知道的一件重要的事情--这个问题的解决方案在不同的IDE之间有很大的不同,但这个简单的解决方案在大多数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>;
。
我希望你会发现它是有帮助的,Korel。
https://stackoverflow.com/questions/50593345
复制相似问题