Some basic details of template in C++

 The introdution of template into C++ makes it more flexible and more capable to support generic design and programming. There are two usages, the template function and the template class. Although they have many characteristics in common, a few subtle differences exist. One may write good programs without knowing these details, however, it will surely help one understand what the program does and how it works better, which results in better implementation and less errors.

The definition of a Template function or a template class should be visible at the calling point, just as the definition of an inline function. The reason is that the compiler should know how it is defined when trying to do the template instantiation (for an inline function, the compiler has to know its definition to replace the function call with the its code). So, if one just puts the declarations in a header file, he may get a compile-time error. The usual solution is to put the definitions as well into the header file, which is called inclusion template compilation mode. Another kind of the template compilation mode is separation mode. As the name shows, using this one, one can put the definition into the corresponding .cpp file, separated from the declaration in the header file. But before the definition, a keyword "export" should be added. It has been introduced into the C++ Standards, however, few compilers support it.

When a template function has the same name of a normal function (or a set of functions), the first step of the function overload resolution will change a little. Besides those normal candidate functions, the template instance which comes from the template argument deduction will also be a candidate. So, as the last paragraph says, the definition of the template should be visible at that calling point (and that is why the template instantiation occurs in compilation time, not in run time). All the other steps remain the same as the normal function overload resolution. Consequently, one can call a template function without explicitly specifying its template arguments because the compiler will do it using deduction implicitly, however, for the declaration or creation of an instance of a template class, it is required.

The template mechanism is really an amazing thing. There are a lot more details to be explored, and it can do a lot of things to make one's design more flexible, more generic, and more powerful.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值