包含模板类型的头文件
我正在编写一个模板类,假设
template <class T>
class bla {
bla() ;
~bla() ;
};
template <class T>
bla<t>::bla(){}
template <class T>
b<t>::~b(){}
只要 T 是 int
、char
等,这就可以正常工作......但如果它是一个自定义类 MyClass
,它将需要包含头文件 MyClass.h
,还是我错了?
问题:如何以类似模板的方式完成此操作,例如
#include "T.h"
干杯!
I'm writing a template class, let's say
template <class T>
class bla {
bla() ;
~bla() ;
};
template <class T>
bla<t>::bla(){}
template <class T>
b<t>::~b(){}
This works fine as long as T is int
, char
, and so on ... but in case that it will be a custom class MyClass
, it will requiere the headerfile MyClass.h
to be included, or am I wrong?
Question: How can this be done in a template-ish way, i.e. something like
#include "T.h"
Cheers!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您使用
bla
时,您需要包含bla
的定义和MyClass
的定义。定义bla
时,不必知道MyClass
。其神奇之处称为“两阶段名称查找”:在编译模板定义时,将查找所有不依赖于模板参数的名称。在第二阶段,当实例化模板时,将在实例化的上下文中查找所有剩余的名称。When you use
bla<MyClass>
you need to have included the definition ofbla
and the definition ofMyClass
. It isn't necessary thatMyClass
is known whenbla
is defined. The magic about this is called "two-phase name look-up": while compiling the template definition all names not depending on the template parameter are looked up. During the second phase, when the template is instantiated, all remaining names are looked up in the context of the instantiation.嗯,事实恰恰相反。如果您想在某个模块(C++ 中的翻译单元)中使用一个类
MyClass
,那么您将包含模板容器(您上面放置的源代码,让其将其命名为container.h
),然后创建数据结构。也许问题是您不知道如何将代码划分为模块。一个简单的经验法则是将每个类放在一个模块中,每个模块都有一个 .h 文件(接口,其中包含所有声明)和 .cpp 文件(实现文件,大致可以在其中编写方法)。
希望这有帮助。
Well, it is the other way round. If you have a class
MyClass
that you want to use in one of your modules (translation units in C++), then you will include the template container (the source code you put above, lets name itcontainer.h
), and then create the data structure.Maybe the problem is that you don not know how to divide your code in modules. A simple rule of thumb is to put each class in a single module, each module with a .h file (the interface, in which all declaration lie), and the .cpp file (the implementation file, where roughly you write the inside of methods).
Hope this helps.