C ++ learning (15) - function template

  • Another C ++ programming ideas called generic programming techniques, the main advantage is the template
  • C ++ template provides two mechanisms: function templates and class templates

1. function template syntax

Function template effect:

To establish a common function, and a function of return value type parameter types may not be specifically customized with a virtual type to represent

Syntax :

template<typename T>
函数定义或声明

Explanation:

template - Create a template declaration

typename - the latter indicating that the symbol is a data type, can be replaced with class

T - a common data type, the name can be replaced, typically uppercase

#include<iostream>
using namespace std;

//函数模板

//两个整型交换的函数
void swapInt(int &a,int &b){
    int temp = a;
    a = b;
    b = temp;
}

//两个浮点型交换的函数
void swapDouble(double &a,double &b){
    double temp = a;
    a = b;
    b = temp;
}

//函数模板
template<typename T> //声明一个模板,告诉编译器后面代码中紧跟着的T不要报错,T是一个通用数据类型
void mySwap(T &a,T &b){
    T temp = a;
    a = b;
    b = temp;
}

void test01(){
    int a = 10;
    int b = 20;
    swapInt(a,b);
    //两种方式使用函数模板
    //1.自动类型推导
    mySwap(a,b);
    //2.显示指定类型
    mySwap<int>(a,b);
    cout << "a = " << a <<endl;
    cout << "b = " << b <<endl;

    double c = 1.1;
    double d = 2.2;
    swapDouble(c,d);
    cout << "c = " << c <<endl;
    cout << "d = " << d <<endl;
}

int main(){

    test01();
    return 0;
}

to sum up:

  • Function template using the keyword template
  • There are two ways to use the template functions: automatic type inference, for a specific type
  • The purpose of the template is to improve the reusability of the type parameter

2. Notes function template

Precautions:

  • Automatic type derivation, must derive the same data type can use T
  • T template must determine the type of data before you can use
//错误,推导不出一致的T类型
int a = 10;
char b = 'c';
mySwap(a,b);
template<class T>
void func(){
    cout << "func调用" << endl;
}
void test02(){
    func();  //错误,编译器无法确定模板的T类型
    func<int>();
}

3. function template Case

Case Description:

  • Function by using a sort function template package can be ordered arrays of different data types
  • Descending collation, sorting algorithm selection sort
  • Using int char array respectively arrays and tested
#include<iostream>
using namespace std;

//实现通用 对数组进行排序的函数
//规则 从大到小
//算法 选择
//测试 char数组、 int数组

//交换函数模板
template<class T>
void mySwap(T &a, T &b){
    T temp = a;
    a = b;
    b = temp;
}

//排序算法
template<class T>
void mySort(T arr[], int len){
    for(int i=0;i<len;i++){
        int max = i;//认定最大值的下标
        for(int j=i+1;j<len;j++){
            if(arr[max]<arr[j]){
                max = j;
            }
        }
        if(max!=i){
            //交换
            mySwap(arr[max],arr[i]);
        }
    }
}

//打印函数模板
template<class T>
void myPrint(T arr[], int len){
    for(int i=0;i<len;i++){
        cout<<arr[i]<<" ";
    }
    cout<<endl;
}

//测试char数组
void test01(){
    char charArr[]="badcfe";
    int len = sizeof(charArr) / sizeof(charArr[0]);
    mySort(charArr,len);
    myPrint(charArr,len);
}

//测试int数组
void test02(){
    int intArr[]={7,5,1,3,9,2,4};
    int len = sizeof(intArr) / sizeof(intArr[0]);
    mySort(intArr,len);
    myPrint(intArr,len);
}

int main(){
    test02();
    return 0;
}

4. The difference between a normal function and function template

The difference between a normal function and function template :

  • Automatic type conversion (implicit type conversion) can occur when an ordinary function call
  • Template function call, if the use of automatic type inference, implicit type conversion does not occur
  • If the specified type using the display mode, implicit type conversion may occur
#include<iostream>
using namespace std;

//普通函数与函数模板区别

//普通函数
int myAdd01(int a, int b){
    return a+b;
}

//函数模板
template<class T>
T myAdd02(T a, T b){
    return a+b;
}

void test01(){
    int a = 10;
    int b = 20;
    char c = 'c';
    cout << myAdd01(a,c) << endl;
    cout << myAdd02<int>(a,c) << endl;
}

int main(){
    test01();
    return 0;
}

Summary : It is recommended to use the specified type of display mode, call the function template, because they can determine their own generic type T

5. Call the rules of ordinary function and function template

Call rules are as follows:

  1. If the function templates and common function can be achieved, priority call ordinary function
  2. You may be forced to call a function by a blank template template parameter list
  3. Overloaded function template can also occur
  4. If the function templates can produce a better match, priority call function template
#include<iostream>
using namespace std;

//普通函数与函数模板调用规则

//普通函数
void myPrint(int a, int b){
    cout << "1" << endl;
}

//函数模板
template<class T>
void myPrint(T a, T b){
    cout << "2" << endl;
}

template<class T>
void myPrint(T a, T b, T c){
    cout << "3" << endl;
}

void test01(){
    int a = 10;
    int b = 20;
    char c = 'c';
    char d = 'd';

    myPrint(a,b);
    myPrint<>(a,b);
    myPrint(a,c);
    myPrint(c,d);
    myPrint(a,b,100);
}

int main(){
    test01();
    return 0;
}

Summary : Since the function template provided, better not to provide general function, ambiguity or prone

6. Limitations template

Limitations :

  • Universal template is not a panacea

E.g:

template<class T>
void f(T a, T b){
    a = b;
}

Assignment provided in the above code, if a and b are passed in an array, can not be achieved

For another example:

template<class T>
void f(T a, T b){
    if(a>=b){...}
}

In the above code, if the data type of the incoming T is like Person-defined data types, are not working

So C ++ To solve this problem, provide a template overloads can for these specific types provide concrete template

#include<iostream>
#include<string>
using namespace std;

//模板的局限性

class Person{
public:
    Person(string name,int age){
        this->m_name = name;
        this->m_age = age;
    }
    string m_name;
    int m_age;
};

//对比两个数据是否相等的函数
template<class T>
bool myCompare(T &a, T &b){
    if(a == b){
        return true;
    }
    return false;
}

//利用具体化Person的版本实现代码,具体化优先调用
template<> bool myCompare(Person &p1, Person &p2){
    if(p1.m_name == p2.m_name &&p1.m_age == p2.m_age){
        return true;
    }
    return false;
}

void test01(){
    int a = 10;
    int b = 20;
    if(myCompare(a,b)){
       cout<<"a==b"<<endl; 
    }else{
        cout<<"a!=b"<<endl;
    }
    
}

void test02(){
    Person p1("Tom", 10);
    Person p2("Tom", 11);
    if(myCompare(p1,p2)){
       cout<<"p1==p2"<<endl; 
    }else{
        cout<<"p1!=p2"<<endl;
    }

}

int main(){
    test02();
    return 0;
}

to sum up:

  • Specific use of templates, you can solve the universal custom type
  • Learning not to write a template template, but in the STL can use the template provided by the system

Guess you like

Origin www.cnblogs.com/maeryouyou/p/12274934.html