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

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.

主站蜘蛛池模板: 台南市| 进贤县| 海兴县| 福清市| 安乡县| 镇安县| 永靖县| 江孜县| 开化县| 专栏| 荆门市| 邵阳县| 全州县| 寿光市| 仙游县| 南京市| 萨嘎县| 巴楚县| 深水埗区| 开原市| 吉林省| 石河子市| 三门县| 遂宁市| 双城市| 遂宁市| 县级市| 陆丰市| 石渠县| 新闻| 新津县| 老河口市| 密云县| 沾益县| 扬中市| 商南县| 吕梁市| 赤水市| 灵丘县| 惠州市| 大名县|