您的位置:首页 > 编程语言 > C语言/C++

Some basic details of template in C++

2008-02-04 00:35 417 查看
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: