Generic parameters of generic programming

One, generic parameters

Question: Use C++ language to achieve the square of a number.

Analysis: A number, can be int, double, complex, etc., the rule is to square the number "x*x"

Pseudo code: sqrt(x)

              return x * x;

Realization 1: Provide a set of squaring functions for different types of numbers.

int sqrtInt(int x)
{
    return x*x;
}

int sqrtDouble(double x)
{
    return x*x;
}

// ...

Implementation 2: The above set of functions has different function names for different number types, which challenge people's memory ability and coding becomes troublesome. The C++ function overloading technology improvement scheme can be used.

int sqrt(int x)
{
    return x*x;
}

int sqrt(double x)
{
    return x*x;
}

// ...

Implementation three: The implementation of the second program means that the more types, the more codes of the same structure, resulting in a large number of duplicate codes, which are prone to errors and difficult to maintain. Here, the generic programming technology in C++ can be used to generalize the above-mentioned function family, that is, generic parameters.

template<typename T>
T sqrt(T x)
{
    return x*x;
}

The first advantage of generic parameters can be seen from the process of program changes: avoid code duplication in statically typed languages.

Further analysis of implementation three, generics also impose operating constraints "x*x" on the parameters, and the parameter types must satisfy the multiplication rule. That is, the second advantage of generic parameters: the operating behavior of constrained parameters. Failure to meet the operating behavior rules will result in compilation failure.

As shown in the example below:

The third advantage: Through the static type checking of the compiler, the correct type can be guaranteed at compile time.

As shown below:

Guess you like

Origin blog.csdn.net/xunye_dream/article/details/115041460