In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
In this issue, Xiaobian will bring you about how to use function templates to implement and optimize abstract operations. The article is rich in content and analyzes and narrates from a professional perspective. After reading this article, I hope you can gain something.
When creating functions that perform abstract operations such as copy, invert, and sort, you must define multiple versions to be able to handle each data type. Take the max() function as an example,
Returns the greater of two parameters:
double max(double first, double second);complex max(complex first, complex second);date max(date first, date second);//.. Other versions of this 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;}
This not only duplication of labor, error-prone, but also brings a lot of maintenance and debugging workload. Worse, even if you don't use a version in your program, its code still increases the size of the executable file, and most compilers will not remove unreferenced functions from the executable file.
Implementing abstract operations with generic functions forces you to define multiple instances of the function, incurring significant maintenance and debugging overhead. The solution is to use function templates instead of regular functions.
Using Function Templates
Function templates solve all of the above problems. Type-independent and instantiates automatically only when needed. The rest of this article shows how to define function templates to abstract common operations, demonstrates how to use them, and discusses optimization techniques.
Step 1: Definition
The declaration of a function template is followed by the keyword template followed by one or more template parameters and prototypes in angle brackets. As opposed to normal functions, which are usually declared in one transformation unit and defined in another, you can define templates in a header file. For example:
// file max.h#ifndef MAX_INCLUDED#define MAX_INCLUDEDtemplate T max(T t1, T t2){ return (t1 > t2) ? t1 : t2;}#endif
Define T as a template parameter, or placeholder, that replaces a specific data type when max() is instantiated. max is the function name, t1 and t2 are its arguments, and the return value is of type T. You can use this max() just as you would a normal function. The compiler automatically generates template specializations, or instances, according to the type of data used:
int n=10,m=16;int highest = max(n,m); //Generate int version std::complex c1, c2;//.. assign std::complex higher=max(c1,c2); // complex version
Step 2: Improve the design
The implementation of max() above is also somewhat rustic-parameters t1 and t2 are passed in terms of values. This is not a problem for built-in data types like int, float. However, for user-defined data types like std::complex and std::sting, it is more efficient to pass parameters by reference. Furthermore, since max() assumes that its parameters are unchangeable, we should declare t1 and t2 as const (constants). Here is an improved version of max():
template T max(const T& t1, const T& t2){ return (t1 > t2) ? t1 : t2;}
Additional performance issues
Fortunately, the Standard Template Library or STL has defined an algorithm called std::max() in. So you don't have to reinvent it. Let's consider a more realistic example, byte sorting. TCP/IP is known to require the use of big endian byte order when transmitting multibyte values. Therefore, the big endian byte order is also known as network byte order. If the destination host uses little endian order, all incoming byte values must be converted to little endian order. Similarly, before multibyte values can be transmitted over TCP/IP, the host must convert them into network byte order. Your socket library declares four functions responsible for converting between host byte order and network 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 do the same thing: invert the bytes of a multibyte value. The only difference is directionality and the size of the parameters. Very suitable for templating. Using a template function instead of these four functions, we can define a clever template that will handle all four cases and many more:
template T byte_reverse(T val);
To determine the actual type of T, we use the sizeof operator. In addition, we also use STL's std::reverse algorithm to invert the bytes of the value:
template T byte_reverse(T val){ //val as byte stream unsigned char *p=reinterpret_cast (&val); std::reverse(p, p+sizeof(val)); return val;}
use method
byte_reverse() template processing works perfectly for all cases. Moreover, it can be flexibly applied to other types that are not supported originally (e.g., 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}
Note: improper use of templates can affect the size of the.exe file, which is a common code bloat problem.
The above is how to use function templates to implement and optimize abstract operations shared by Xiaobian. If there are similar doubts, please refer to the above analysis for understanding. If you want to know more about it, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.