官术网_书友最值得收藏!

  • Expert C++
  • Vardan Grigoryan Shunguang Wu
  • 277字
  • 2021-06-24 16:34:05

Syntax

There are two ways to define function templates, as shown in the following code:

template <typename identifier_1, …, typename identifier_n > 
function_declaration;

template <class identifier_1,…, class identifier_n>
function_declaration;

Here, identifier_i (i=1,…,n) is the type or class parameter and function_declaration declares the function body part. The only difference in the preceding two declarations is the keywords one uses class while the other uses typename, but both have the same meaning and behavior. Since a type (such as the basic types int, float, double,enum, struct, union, and so on) is not a class, the typename keyword method was introduced to avoid confusion.

For example, the classic find maximum value function template, app_max(), can be declared as follows:

template <class T>
T app_max (T a, T b) {
return (a>b?a:b); //note: we use ((a)>(b) ? (a):(b)) in macros
} //it is safe to replace (a) by a, and (b) by b now

This function template can work for many data types or classes, as long as there's a copy-constructible type where the a>b expression is valid. For user-defined classes, this means that the greater-than operator (>) must be defined.

Note that the function template and template function are different things. Function template refers to a kind of template that's used to generate functions by a compiler, so the compiler does not generate any object code for it. On the other hand,template function means an instance from a function template. Since it is a function, the corresponding object code is generated by the compiler. However, the latest C++ standard documents suggest avoiding using the imprecision term template function. Therefore, we will use function templates and member function templates in this book.

主站蜘蛛池模板: 巴林左旗| 醴陵市| 金湖县| 阳新县| 龙门县| 兰溪市| 迁安市| 托克托县| 赫章县| 东至县| 墨竹工卡县| 南乐县| 祥云县| 平乡县| 团风县| 安仁县| 庆安县| 武义县| 青田县| 东阳市| 通州市| 兴安县| 潢川县| 洪江市| 汉川市| 修水县| 崇义县| 五峰| 渝中区| 福贡县| 漳州市| 鸡泽县| 乌恰县| 楚雄市| 罗源县| 宁南县| 平邑县| 读书| 阜宁县| 云浮市| 辽宁省|