C++ function templates and class templates

1-1 Why use function templates?

#include <iostream>
using namespace std;
/*
void myswap(int &a, int &b)
{
    int t = a;
    a = b;
    b = t;
}

void myswap(char &a, char &b)
{
    char t = a;
    a = b;
    b = t;
}
*/

//template 关键字告诉C++编译器 我要开始泛型了.你不要随便报错  
//数据类型T 参数化数据类型
template <typename T>
void myswap(T &a, T &b)
{
    T t;
    t = a;
    a = b;
    b = t;
}

void main()
{
    //char a = 'c';

    int  x = 1;
    int  y = 2;
    myswap(x, y); //自动数据类型 推导的方式 

    float a = 2.0;
    float b = 3.0;

    myswap(a, b); //自动数据类型 推导的方式 
    myswap<float>(a, b); //显示类型调用 

    cout<<"hello..."<<endl;
    system("pause");
    return ;
}

1-2 Function templates can be used as function parameters

#include <iostream>
using namespace std;

template<typename T, typename T2>
void sortArray(T *a, T2 num)
{
    T tmp ;
    int i, j ;
    for (i=0; i<num; i++)
    {
        for (j=i+1; j<num; j++)
        {
            if (a[i] < a[j])
            {
                tmp = a[i];
                a[i] = a[j];
                a[j] = tmp;
            }
        }
    }
}

template<class T>
void pirntArray(T *a, int num)
{
    int i = 0;
    for (i=0; i<num; i++)
    {
        cout<<a[i]<<" ";
    }
}

void main()
{
    int num = 0;
    char a[] = "ddadeeettttt";
    num = strlen(a);

    printf("排序之前\n");
    pirntArray<char>(a, num);

    sortArray<char, int>(a, num); //显示类型调用 模板函数 <>
    printf("排序之后\n");
    pirntArray<char>(a, num);
    cout<<"hello..."<<endl;
    system("pause");
    return ;
}

1-3 Function template encounters function overloading

Difference between function templates and ordinary functions Conclusion:
function templates do not allow automatic type conversion,
ordinary functions can perform automatic type conversion

Function templates and ordinary functions together, calling rules:
1 Function templates can be overloaded like ordinary functions
2 C++ compilers give preference to ordinary functions
3 If the function template can produce a better match, then choose the template

Take a look at the following case analysis:

#include <iostream>
using namespace std;

template <typename T>
void myswap(T &a, T &b)
{
    T t;
    t = a;
    a = b;
    b = t;
    cout<<"myswap 模板函数do"<<endl;
}

void myswap(char &a, int &b)
{
    int t;
    t = a;
    a = b;
    b = t;
    cout<<"myswap 普通函数do"<<endl;
}

void main()
{
    char cData = 'a';
    int  iData = 2;

    //myswap<int>(cData, iData);  //结论 函数模板不提供隐式的数据类型转换  必须是严格的匹配

    myswap(cData, iData); 
    //myswap(iData, cData);

    cout<<"hello..."<<endl;
    system("pause");
    return ;
}

1-4 Function template mechanism conclusion:

The compiler does not treat the function template as a function that can handle any class. The
compiler generates different functions from the function template by the concrete type. The
compiler compiles the function template twice. The template code itself is compiled
at the point of declaration; where the code after parameter substitution is compiled.

2.1 Class templates can be declared and used like this:

1) Write an actual class first. Because of its clear semantics and clear meaning, it is generally not wrong.
2) Change the type name to be changed in this class (for example, int to be changed to float or char) with a virtual type name specified by yourself.
3) Add a line before the class declaration, the format is:

 template <class 虚拟类型参数>

Such as:

 template <class numtype> //注意本行末尾无分号
    class Compare
    {…}; //类体

4) When defining an object with a class template, use the following form:

   类模板名<实际类型名> 对象名;
    类模板名<实际类型名> 对象名(实参表列);

Such as:

    Compare<int> cmp;
    Compare<int> cmp(3,7);

5) If a member function is defined outside a class template, it should be written in the form of a class template:

   template <class 虚拟类型参数>
      函数类型 类模板名<虚拟类型参数>::成员函数名(函数形参表列) {…}

2.2 A few notes about class templates:

1) The type parameter of the class template can have one or more, and each type must be preceded by a class, such as:

  template <class T1,class T2>
    class someclass
    {…};

Substitute the actual type name when defining the object, such as:

    someclass<int,double> obj;

2) As with classes, when using a class template, pay attention to its scope , and can only use it to define objects within its effective scope.
3) Templates can have hierarchies, and a class template can be used as a base class to derive derived template classes.

2.3 Application of class template in project development

Summary
 Templates are polymorphic tools for C++ type parameterization. C++ provides function templates and class templates.
 A template definition begins with a template description. Generic parameters must appear at least once in the template definition.
 The same generic parameter can be used in multiple templates.
 Generic parameters can be used for function parameter types, return types, and variables in declared functions.
 Templates are instantiated by the compiler according to the actual data type to generate executable code. Instantiated function.
Templates are called template functions; instantiated class templates are called template classes.
 Function templates can be overloaded in many ways.
 Class templates can be used in class hierarchies.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325485660&siteId=291194637