Templates and multiple-file projects

From the point of view of the compiler, templates are not normal functions or classes. They are compiled on
demand, meaning that the code of a template function is not compiled until an instantiation with specific template
arguments is required. At that moment, when an instantiation is required, the compiler generates a function
specifically for those arguments from the template.


When projects grow it is usual to split the code of a program in different source code files. In these cases, the
interface and implementation are generally separated. Taking a library of functions as example, the interface
generally consists of declarations of the prototypes of all the functions that can be called. These are generally
declared in a "header file" with a .h extension, and the implementation (the definition of these functions) is in an
independent file with c++ code.


Because templates are compiled when required, this forces a restriction for multi-file projects: the implementation
(definition) of a template class or function must be in the same file as its declaration. That means that we cannot
separate the interface in a separate header file, and that we must include both interface and implementation in any
file that uses the templates.
Since no code is generated until a template is instantiated when required, compilers are prepared to allow the
inclusion more than once of the same template file with both declarations and definitions in a project without
generating linkage errors.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值