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

Motivation

So far,when we have defined a function or a class, we have had to provide input, output, and intermediate parameters. For example, let's say we have a function to performs the addition of two int type integers. How do we extend this so that it handles all the other basic data types, such as float, double, char, and so on? One way is to use function overloading by manually copying, pasting, and slightly modifying each function. Another way is to define a macro to do the addition operation. Both approaches have their own side effects.

Moreover, what happens if we fix a bug or add a new feature for one type, and this update needs to be done for all the other overloading functions and classes later? Instead of using this silly copy-paste-and-replacement method, do we have a better way of handling this kind of situation?

In fact, this is a generic problem that any computer language can face. Pioneered by the general-purpose functional programming Meta Language (ML) in 1973, ML permits writing common functions or types that differ only in the set of types that they operate on when used, thus reducing duplication. Later inspired by the parameterized modules provided in the chartered life underwriter (CLU) and the generics provided by Ada, C++ adopted the template concept, which allows functions and classes to operate with generic types. In other words, it allows a function or class to work on different data types without them needing to be rewritten.

Actually, from an abstract point of view, C++ functions or class templates (such as cookie cutters) serve as a pattern for creating other similar functions or classes. The basic idea behind this is to create a function or class template without having to specify the exact type(s) of some or all variables. Instead, we define a function or class template using placeholder types, called template type parameters. Once we have a function or class template, we can automatically generate functions or classes by using an algorithm that has been implemented in other compilers.

There are three kinds of templates in C++: function templates, class templates, and variadic templates. We'll take a look at these next.

主站蜘蛛池模板: 海兴县| 云安县| 栾川县| 开远市| 仪陇县| 新巴尔虎右旗| 鄯善县| 嘉禾县| 马公市| 鄂托克旗| 商城县| 合阳县| 繁昌县| 临颍县| 景宁| 邳州市| 辽宁省| 政和县| 奉新县| 抚州市| 五大连池市| 泌阳县| 宁都县| 阿城市| 竹北市| 正安县| 潜山县| 沙洋县| 济南市| 张家口市| 会泽县| 松阳县| 德钦县| 株洲市| 牙克石市| 五华县| 舟山市| 玉溪市| 平谷区| 太康县| 福泉市|