Use template to replace overload

xiaoxiao2021-03-05  27

By Yazy - 2005, 04.23

If we want to implement a function that supports multiple input types, we can use "overload" in C : void test (int N) {cout << "test (int): << n << endl;}

Void test (float n) {cout << "test (float):" << n << endl;}

Void test (short): "<< n << endl;} The overload is to implement a function entity for each specific type. This approach may bring great convenience to the user of the function, this convenient manifestation is only necessary to remember a function, without having to use its specific function calls for different types, because "overload" This "selection" is given to the selection. So "overload" is helpful for users to develop programs to help code multiplex efficiency.

The disadvantage of overload is: it has aggravated the development burden of function developers. According to the "User-centered" idea, overload the sacrifice developers more time and energy, in exchange for more user interests. The author needs to have more efforts to refer to the same function to write multiple versions; the author must guarantee that each version of the function is correct or is usually a uniform semantic. Maybe developers should have more, and sometimes complex problems make this guarantee to become less meaningful.

The Template of C can be generically used. For example, in a function may use an unknown type T, it may be int, float, short, or a certain type of custom type. Template allows developers to use this "unknown" to reserve this "unknown" state to function and the code is added. This type of "unknown" is "generalized type", which uses such programming paradigms known as "generic programs".

The above TEST uses generic programming methods to be: Template void test (t n) {cout << "template void test (t): << n << Endl;}

Compared to "overload", generic functions can be applied to more types, or even difficult to determine how many types it can be used, and the overload function is typically used for extremely limited number of types.

The generic function usually only requires the input type to meet certain features, and it is ignored that it is specific. For example, a generic function may require an input type to participate in an arithmetic operation, logical operation, or a certain interface (such as Iterator in STL).

In C , you can also "pan" constant, which is about to "unknown" state to give a constant: Template void test (t n) {int NUMS [size]; // ... cout < <"Size:" << size << Endl << "Para:" << n << endl;}

The generics also include: default template parameters, specialization, etc. Have to learn ...

转载请注明原文地址:https://www.9cbs.com/read-32797.html

New Post(0)