多文件模板实现 [英] Multiple-File Template Implementation

查看:50
本文介绍了多文件模板实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于普通函数,声明和定义通常跨多个文件分开,例如:

With normal functions, the declaration and definition are often separated across multiple files like so:

// Foo.h

namespace Foo
{
    void Bar();
}

.

// Foo.cpp

#include "Foo.h"

void Foo::Bar()
{
    cout << "Inside function." << endl;
}

据我了解,这无法使用模板完成.声明和定义不得分开,因为会在需要时按需创建模板的适当形式.

It is my understanding that this cannot be done with templates. The declaration and definition must not be separate because the appropriate form of the template is created "on-demand" when needed.

那么,在这样的多文件项目中,模板的定义方式和位置通常是什么?我的直觉是,它将放在 Foo.cpp 中,因为这通常是函数的肉"所在的位置,但是另一方面,将包含头文件.

So, how and where are templates typically defined in a multiple-file project like this? My intuition is that it would be in Foo.cpp because that's where the "meat" of functions normally is, but on the other hand it's the header file that's going to be included.

推荐答案

模板代码保留在 .hh 文件中.尽管将定义放在 all 声明之后是很好的做法,但没有理由将它们分开放置.

Template code stays in the .hh file. There's no reason to make them separate files, though it is good practice to put the definitions after all the declarations.

当编译器生成模板代码时,会对其进行标记,以便链接器知道一个编译单元(即 .o 文件)中模板的实例化与另一个模板中的代码完全相同.单元.它将保留一个并丢弃其余的,而不是因出现多重定义的符号"错误而解决.

When the compiler generates template code, it flags it so that the linker knows that the instantiation of a template in one compilation unit (i.e. .o file) is the exact same code as one in another unit. It will keep one and discard the rest, rather than bailing out with a "multiply defined symbol" error.

对于具有良好模板支持的现代编译器而言,这是正确的.在GCC的情况下,从2.8开始.(我知道,在gcc 2.7.2.2编写了链接器之前,我已经写了很多代码,因此您必须跳过箍以使模板正确构建.)

This is true of modern compilers with good template support. In the case of GCC, since 2.8. (I know, I wrote a lot of code for gcc 2.7.2.2 before they smartened the linker up and you had to jump through hoops to make templates build right.)

这篇关于多文件模板实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆