Easyc ++ 41, template explicitly

Hello everyone, I am Liang Tang.

This is the 41st article of the EASYC ++ series to talk about the template explicitly.

I want to pursue a better reading experience, I can visit the Github Warehouse: EasyleetCode.

The previous article said, although the template function is very easy, there are some problems. For example, an operation is not applicable to all types, which provides a solution for this case C ++, which is a template definition for specific types. The specific specificity of the specifically here can be understood.

Let’s take a look at the example in C ++ Primer, suppose now we have a structure called Job:

For structures, it can be assigned a whole, so the previous SWAP function is the same as it.

But we now hope that when switching structures, just exchange SALARY and FLOOR two fields, keeping Name unchanged. Since we want to introduce logical changes, it is not feasible to call the SWAP function directly.

Of course we don’t have to function template, direct overload function:

Since the C ++ is specified, the priority of the non-function template is greater than the function template, so we will use this when we call the SWAP function for the Job structure.

In addition, we can provide a specific template function:

The writing of this function seems to be special. We added Template <> before the function type, and followed the <Job> after the function name. It represents this is an explicit specificization of a function template, or it is understood that the previous function template provides a Job type version. The priority of the explicit template function is higher than the ordinary template function.