- 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.
- 微信公眾平臺與小程序開發(fā):從零搭建整套系統(tǒng)
- 算法零基礎一本通(Python版)
- Mastering Concurrency in Go
- 軟件測試項目實戰(zhàn)之性能測試篇
- 從程序員到架構師:大數(shù)據(jù)量、緩存、高并發(fā)、微服務、多團隊協(xié)同等核心場景實戰(zhàn)
- 深入分布式緩存:從原理到實踐
- Learning Probabilistic Graphical Models in R
- 精通MySQL 8(視頻教學版)
- Modern C++ Programming Cookbook
- Oracle數(shù)據(jù)庫編程經(jīng)典300例
- 一步一步跟我學Scratch3.0案例
- Mastering HTML5 Forms
- ArcPy and ArcGIS(Second Edition)
- 和孩子一起學編程:用Scratch玩Minecraft我的世界
- 軟件自動化測試實戰(zhàn)解析:基于Python3編程語言