The concept and meaning of a class template

Concept and significance class template
class template
classes mainly used for storing and organizing data elements of
the class regardless of the particular type of embodiment of the data organization and data elements
such as: an array type, list type, class Stack, Queue the like
in the C ++ template of the ideology of class, making implementation class does not focus on specific types of data elements, and only concerned with the class needs to implement functionality

Template class in C ++
- In the same manner different types
- are identified prior to use template class declaration
- <typename T> refers to the type described for use in class T
template <typename T>
class the Operator
{
public:
  T OP (T A, T B);
};

Application class template
- only specify the particular type of display, it can not be derived automatically
- using the particular type <Type> definition object
the Operator <int> OP1;
the Operator <String> OP2;
int I = op1.op (1,2);
String S = op2.op ( "DT", " Software");

It refers declaration type T can be anywhere on the class template
compiler for handling the same type and function template template
- from the class templates generated by the particular type of different classes
- the class template code itself is compiled statement where
- in compiling the code after replacing the parameters used elsewhere

#include <iostream>
#include <string>

using namespace std;


template<typename T>
class Operator
{
public:
    T add(T a, T b)
    {
        return a + b;
    }
    T minus(T a, T b)
    {
        return a - b;
    }
    T multiply(T a, T b)
    {
        return a * b;
    }
    T divide(T a, T b)
    {
        return a / b;
    }
};

int main()
{
    The Operator < int > OP1; 
    COUT << op1.add ( . 1 , 2 ) << endl; 

    the Operator < String > OP2; 
    COUT << op2.add ( " Hello " , " World " ) << endl;
     // COUT < <op2.minus ( "Hello", "World") << endl; // error. Because subtract two string objects, not defined in C ++. 

    return  0 ; 
}

类模板的工程应用:注意这三部分不是C++规范的一部分,也不是C++编译器要求必须这样做。只不过工程上的一种好的习惯
-类模板必须在头文件中定义
-类模板不能分开实现在不同的文件中
-类模板外部定义的成员函数需要加上模板<>声明

#ifndef OPERATOR_H
#define OPERATOR_H

template<typename T>
class Operator
{
public:
    T add(T a, T b);
    T minus(T a, T b);
    T multiply(T a, T b);
    T divide(T a, T b);

};

template<typename T>
T Operator<T>:: add(T a, T b)
{
    return a + b;
}
T Operator<T>:: minus(T a, T b)
{
    return a - b;
}
T Operator<T>:: multiply(T a, T b)
{
    return a * b;
}
T Operator<T>:: divide(T a, T b)
{
    return a / b;
}

#endif // OPERATOR_H

小结:
泛型编程的思想可以应用于类
类模板以相同的方式处理不同类型的数据
类模板非常适用于编写数据结构相关的代码
类模板在使用时只能显示指定类型

Guess you like

Origin www.cnblogs.com/-glb/p/11992557.html