C++: Generic Programming

template

template function

The basic usage rules for templates are as follows:

template<typename T>
void m_swap(T &num1, T &num2){
    
    
    T temp = num1;
    num1 = num2;
    num2 = temp;
}

int main(int argc, char const *argv[])
{
    
    
    int num1 = 10;
    int num2 = 20;
    //自动类型推导调用
    m_swap(num1, num2);
    cout << num1 << endl;
    cout << num2 << endl;

    double num3 = 10.0;
    double num4 = 7.6;
    //显示指定类型调用
    m_swap<double>(num3, num4);
    cout << num3 << endl;
    cout << num4 << endl;

    return 0;
}

Note: When using templates, the general data type T must be determined and a consistent type can be derived.

Calling Rules for Ordinary Functions and Template Functions

  • If both the template function and the normal function are implemented, the normal function is called first
  • Function templates can be forced to be invoked with an empty template parameter list
  • Function templates can be overloaded
  • If the template function can produce a better match, the template function is called in preference

template class

The basic usage of the template class is as follows:

template<typename nameType, typename ageType>
class Student {
    
    
    public:
        nameType name;
        ageType age;
    
    public:
        Student(nameType name, ageType age) {
    
    
            this->name = name;
            this->age = age;
        }

        void ShowName(){
    
    
            cout << this->name << endl;
        }
};

int main(int argc, char const *argv[]) {
    
    
    Student<string, int> stu("xiaoming", 18);
    stu.ShowName();

    system("pause");
    return 0;
}

References

Guess you like

Origin blog.csdn.net/xuyangcao123/article/details/124823360