Article Directory
understanding
A template is a tool to implement a code reuse mechanism . The template is usually used in a larger code base for the purpose of achieving code reusability and program flexibility. It can realize type parameterization, that is, the type is defined as a parameter, thus realizing the real code reusability. Templates can be divided into two categories, one is function templates, and the other is class templates.
1. Function template:
- Single ordinary function : can only handle a set of data types.
- Function overloading : operate on different sets of data
- Single function template : can handle different data types at once, but with less code
Declaration method:
//T is a template parameter, which accepts different data types (such as int, float, etc.), and class is a keyword. You can use the keyword typename instead
classtemplate
T someFunction(T arg)
{ … … …}
Function template code:
#include <iostream>
using namespace std;
// template function
//template <class T>
template <typenameT>//class和typename都可以
T Larger(T n1, T n2)
{
return (n1 > n2) ? n1 : n2;
}
int main()
{
int i1 = 10, i2 = 23;
float f1 = 3.4, f2 = 5.8;
char c1 = 'A', c2 = 'N';
cout << "输入两个整数:\n";
cout << Larger(i1, i2) <<" 更大。" << endl;
cout << "\n输入两个浮点数:\n";
cout << Larger(f1, f2) <<" 更大。" << endl;
cout << "\n输入两个字符:\n";
cout << Larger(c1, c2) << " 具有较大的ASCII值。";
return 0;
}
2. Class template
Declaration method:
//T is a template parameter, which is a placeholder for the data type used. Inside the class, the member variable var and the member function someOperation() are of type T. For the function, see if it needs a return value .
//It can be called from within the class or with an object
template class className
{
… … …
public: T var;
T someOperation(T arg);
… … …
};
Use: create class template objectclassName classObject;
E.g:
className classObject;
className classObject;
className classObject;
Reference Code:
#include <iostream>
using namespace std;
template <class T>
class Calculator
{
private:
T num1, num2;
public:
Calculator(T n1, T n2)
{
num1 = n1;
num2 = n2;
}
void displayResult()
{
cout << "Numbers are: " << num1 << " and " << num2 << "." << endl;
cout << "Addition is: " << add() << endl;//以下都是class内部调用
cout << "Subtraction is: " << subtract() << endl;
cout << "Product is: " << multiply() << endl;
cout << "Division is: " << divide() << endl;
}
T add() {
return num1 + num2; }
T subtract() {
return num1 - num2; }
T multiply() {
return num1 * num2; }
T divide() {
return num1 / num2; }
T test(){
cout<<"test"<<endl; return num1;}
};
int main()
{
Calculator<int> intCalc(2, 1);//创建类模板对象
Calculator<float> floatCalc(2.4, 1.2);//创建类模板对象
cout << "Int results:" << endl;
intCalc.displayResult();
cout << endl << "Float results:" << endl;
floatCalc.displayResult();
intCalc.test();//对象调用类模板的T成员
return 0;
}