Use of function templates in C + +

Source: Internet
Author: User

In programming, we often use the same function as the function body, if we want to decide which function to invoke depending on the parameter table we use, we often use the function overloading, but when we have a lot of functions we find it inconvenient to implement. So C + + provides the concept of a function template, which is similar to the way a class template is implemented.

For example, we often want to use the bubbling sorting algorithm, the object being sorted may be double,int,char,float, and so on, here is the implementation code:

Template <typename t1,typename t2>void bubble (T1 *a, T2 len) {T1 temp;for (int i=0;i<len;i++) {for (int j=i;j< len;j++) {if (A[i]>a[j]) {temp=a[i]; A[I]=A[J]; a[j]=temp;}}}}
This allows us to make a specific function call based on the type of object being sorted.


Use of function templates in C + +

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.