C ++ uses function templates to implement and optimize abstract operations

Source: Internet
Author: User
When creating an abstract function, such as copy, reverse, and sort, you must define multiple versions to process each data type. Take the max () function as an example. It returns the greater of the two parameters:

Double max (double first, double second );
Complex max (complex first, complex second );
Date max (date first, date second );

// .. Other versions of the Function

Although the implementation of this function is the same for different data types, the programmer must define a separate version for each data type:

Double max (double first, double second)
{
Return first> second? First: second;
}

Complex max (complex first, complex second)
{
Return first> second? First: second;
}

Date max (date first, date second)
{
Return first> second? First: second;
}

In this way, not only repetitive work, but also error-prone, and bring a lot of maintenance and debugging workload. Worse, even if you do not use a specific version in the program, the Code still increases the size of the executable file, and most compilers will not delete unreferenced functions from the executable file.

Abstract operations using common functions will force you to define multiple function instances, resulting in a large amount of maintenance and debugging costs. The solution is to use a function template instead of a common function.

Use function templates

The function template solves all the above problems. The type is irrelevant and is automatically instantiated only when needed. This article will show you how to define a function template to Abstract Common Operations, demonstrate how to use it, and discuss optimization technologies.

Step 1: Define

The declaration of a function template is the parameter and prototype of one or more templates in the sharp arc following the keyword template. Relative to a common function, it is usually declared in a conversion unit, and defined in another unit, you can define a template in a header file. For example:

// File max. h
# Ifndef MAX_INCLUDED
# Define MAX_INCLUDED
Template <class T> T max (T t1, T t2)
{
Return (t1> t2 )? T1: t2;
}
# Endif

<Class T> defines T as a template parameter or placeholder. When max () is instantiated, it replaces the specific data type. Max is the function name, t1 and t2 are its parameters, and the return value type is T. You can use this max () as you use a common function (). The compiler automatically generates the corresponding template specialization according to the data type used, or an instance:

Int n = 10, m = 16;
Int highest = max (n, m); // generate the int version.

Std: complex <double> c1, c2;
//... Assign values to c1 and c2
Std: complex <double> higher = max (c1, c2); // complex version

Step 2: improve the design

The above implementation of max () is somewhat rustic-parameters t1 and t2 are passed by values. It is not a problem for built-in data types such as int and float. However, for user-defined data types such as std: complex and std: sting, passing parameters through references is more effective. In addition, because max () will think that its parameters will not be changed, we should declare t1 and t2 as const (constant ). The following is an improved version of max:

Template <class T> T max (const T & t1, const T & t2)
{
Return (t1> t2 )? T1: t2;
}

Additional performance problems

Fortunately, the standard template library or STL has defined an algorithm named std: max () in <algorithm>. Therefore, you do not have to re-invent it. Let's consider a more realistic example, that is, byte sorting. As we all know, the TCP/IP protocol requires the big endian byte order when transmitting multi-byte values. Therefore, the big endian byte order is also known as the network byte order ). If the target host uses the little endian order, all byte values must be converted to the little endian order. Similarly, before transmitting multi-byte values through TCP/IP, the host must convert them to the network byte order. Your socket library declares four functions, which are responsible for the conversion between the host's byte order and the network's byte order:

Unsigned int htonl (unsigned int hostlong );
Unsigned short htons (unsigned short hostshort );
Unsigned int ntohl (unsigned int netlong );
Unsigned short ntohs (unsigned short netshort );

These functions implement the same operation: reverse the multibyte value. The only difference is the directionality and parameter size. It is very suitable for templatification. Using a template function to replace these four functions, we can define a smart template that will handle all these four situations and more:

Template <class T> T byte_reverse (T val );

To determine the actual type of T, we use the sizeof operator. In addition, we also use the STL std: reverse Algorithm to reverse the value byte:

Template <class T> T byte_reverse (T val)
{
// Use val as the byte stream
Unsigned char * p = reinterpret_cast <unsigned char *> (& val );
Std: reverse (p, p + sizeof (val ));
Return val;
}

Usage

Byte_reverse () template processing is applicable to all situations. Moreover, it can be flexibly applied to other types that are not supported by the original (for example, 64-bit and 128-bit) without modifying any code:

Int main ()
{
Int n = 1;
Short k = 1;
_ Int64 j = 2, I;
Int m = byte_reverse (n); // reverse int
Int z = byte_reverse (k); // reverse short
K = byte_reverse (k); // un-reverse k
I = byte_reverse (j); // reverse _ int64
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.