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

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.

主站蜘蛛池模板: 陇南市| 巩留县| 额敏县| 泸西县| 宁陕县| 庄河市| 章丘市| 乌兰县| 长治县| 萝北县| 星座| 会泽县| 阿勒泰市| 阳新县| 泰和县| 海伦市| 罗平县| 南江县| 黄山市| 上虞市| 通化市| 武川县| 四平市| 海淀区| 开阳县| 两当县| 西昌市| 攀枝花市| 鹤庆县| 安溪县| 田阳县| 墨脱县| 长宁区| 怀远县| 渭源县| 新野县| 滦南县| 昌平区| 图片| 孝感市| 西乡县|