简体   繁体   English

在cpp文件中实现非模板类的模板成员

[英]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.

相关问题 .cpp文件中模板类的非模板方法-未定义引用? - Non-template methods of a template class in .cpp file - Undefined reference? 作为朋友的非模板类的模板成员 - Template member of a non-template class as a friend 当我将带有非模板类的模板类放在同一cpp文件中时出现链接错误-C ++ - Link error when I put template class with non-template classes in same cpp file - C++ C ++非模板类的朋友成为模板类的成员 - c++ non-template class friends to a member of template class 专门化非模板类的成员函数模板 - Specializing member function template of a non-template class 非模板类T的模板成员函数(在T类型上) - Template member function (on type T) of non-template class T 专门研究非模板类的可变参数模板成员函数 - Specialising a variadic template member function of a non-template class 有没有办法在非模板 class 中定义模板成员? #2 - Is there a way to define a template member in a non-template class? #2 非模板类中的模板成员函数-如何定义和调用 - Template member function in a non-template class - how to define and call 使用cstring类型的模板作为非模板类​​中的数据成员 - Use a template with cstring type as a data member in a non-template class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM