模板函数和类在不同文件中的使用
我想要在一个文件中定义一个模板函数并在多个文件中使用。这与常规函数原型的工作方式相同吗?那么我可以定义一次并将原型包含在其他文件中吗?我对类有同样的问题,是否必须在每个头文件中包含模板类的完整定义,就像对类一样?如果我在单独的文件中两次定义模板函数,是否会导致错误,或者是否会未经检查。
还有一个问题,模板函数原型的格式是什么?
I want to have a template function defined in one file and used in many files. Does this work the same way regular function prototypes work? So I can define it once and just include the prototype in other files? I have the same question for classes, must I include the full defintion of a template class in each header file, just as I would for a class? Would it cause and error if I defined a template function twice in separate files or would this just go unchecked.
One more question, what is the format for a template function prototype?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,它与常规函数不同。对于常规函数,您可以
在标头中声明,在某些源文件中定义函数,例如 foo.cc,#include 标头到任何必须使用这些函数的源文件中,例如
bar.cc
,然后让链接器完成剩下的工作。编译器将编译bar.cc
并生成bar.o
,确信您已经在某处定义了函数,如果没有,您将获得一个链接-时间错误。但如果您使用模板:
尝试想象它会如何工作。源文件
foo.cc
和bar.cc
是独立的,彼此一无所知,除了它们都同意 #include 的标头中的内容(这就是整个主意)。所以bar.cc
不知道foo.cc
是如何实现的,而foo.cc
也不知道bar 是什么。 cc
将处理这些函数。在这种情况下,foo.cc
不知道bar.cc
将为 T 指定什么类型。那么,foo.cc
怎样才能为世界上的每个类型名提供定义呢?它不能,所以这种方法是不允许的。您必须在标头中包含整个模板,以便编译器可以为
foo(int)
、或foo(string)
或foo 定义(myWeirdClass)
,或任何bar.cc
调用的内容,并将其构建到bar.o
中(或者如果模板对该类型没有意义,则抱怨) 。课程也是如此。
模板专业化的规则略有不同,但在尝试高级技术之前,您应该很好地掌握基础知识。
No, it's not the same as a regular function. With a regular function, you can declare
in a header, define the functions in some source file, such as
foo.cc
, #include the header in any source file that has to use those functions, such asbar.cc
, and let the linker do the rest. The compiler will compilebar.cc
and producebar.o
, confident that you've defined the functions somewhere, and if you haven't then you'll get a link-time error.But if you're using a template:
try to imagine how that would work. The source files
foo.cc
andbar.cc
are independent and know nothing about each other, except that they agree on what's in the headers they both #include (that's the whole idea). Sobar.cc
doesn't know howfoo.cc
implements things, andfoo.cc
doesn't know whatbar.cc
will do with these functions. In this scenario,foo.cc
doesn't know what typebar.cc
will specify for T. So how canfoo.cc
possible have definitions for every typename under the sun?It can't, so this approach isn't allowed. You must have the whole template in the header, so that the compiler can gin up a definition for
foo(int)
, orfoo(string)
, orfoo(myWeirdClass)
, or whateverbar.cc
calls for, and build it intobar.o
(or complain if the template makes no sense for that type).The same goes for classes.
The rules are a little different for template specializations, but you should get a good grip on the basics before trying the advanced techniques.
请参阅此常见问题解答。特别是,第 12、13 和 14 项涉及分离模板函数的声明和定义。
See this FAQ. Especially, items 12, 13 and 14 deals with separating the declaration and definition of template functions.