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

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

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.

主站蜘蛛池模板: 晴隆县| 尚志市| 潜江市| 安远县| 湖口县| 四川省| 五家渠市| 仪陇县| 韶关市| 泾川县| 苍梧县| 阳江市| 安阳县| 诏安县| 嵊州市| 六枝特区| 托里县| 舟曲县| 沙坪坝区| 西林县| 静乐县| 江都市| 南涧| 合江县| 屏边| 崇阳县| 鲁甸县| 杭锦旗| 深圳市| 高陵县| 保定市| 乾安县| 苍山县| 盐边县| 兴业县| 通渭县| 监利县| 金阳县| 罗城| 宣恩县| 梅州市|