[英]Implement template member of non-template class in cpp file
I have a class: 我有一堂课:
// A.h
class A
{
void foo();
template <class T> void bar( T someVar );
}
#include "A.tcpp"
When I build it, I get linker errors. 构建它时,出现链接器错误。 However, if the whole class would be a template, then the above example would build perfectly fine.
但是,如果整个类都是模板,那么上面的示例将构建得很好。 So my question is:
所以我的问题是:
How do I stick to the pattern of having ALL definitions in the cpp file, when having template member functions as opposed to having a template class? 使用模板成员函数而不使用模板类时,如何坚持在cpp文件中具有所有定义的模式?
If you are going to split aa class that has template functions and non template functions into a header file and a tcpp file then you only put the template definitions in the tcpp file. 如果要将具有模板功能和非模板功能的类拆分为头文件和tcpp文件,则只需将模板定义放在tcpp文件中。 The non template definitions still needs to go into a regular cpp file.
非模板定义仍然需要放入常规cpp文件中。
Putting the non template code in the tcpp file includes it back into the header file and then that means it gets defined in every translation unit it gets included into. 将非模板代码放入tcpp文件中,会将其重新包含在头文件中,这意味着它将在包含在其中的每个翻译单元中进行定义。
In this case that means you should have 在这种情况下,这意味着您应该
// A.h
class A
{
void foo();
template <class T> void bar( T someVar );
}
#include "A.tcpp"
// A.tcpp
template <class T> void A::bar( T someVar ) { some code; }
// A.cpp
#include "A.h"
void A::foo() { some code; }
I found the solution, it is not as nice as I would like, but it will do in my case. 我找到了解决方案,它虽然不尽如人意,但对我而言还是可以的。 We can insert the following line at the end of the tcpp file:
我们可以在tcpp文件的末尾插入以下行:
template void A::bar<int>( int );
// And so on, for all types that should be supported.
It is called function template instantiation . 称为功能模板实例化 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.