在c++中是否可以将泛型编程的思想应用于类?
1.类模板
—-一些类主要用于存储和组织数据元素
—-类中数据组织的方式合数据元素的具体类型无关
—-如:数组类,链表类,stack类,queue类等
c++中将模板的思想应用于类,是类的实现不关注数据元素的具体类型,而只关注类所需要实现的功能
2.c++中的类模板
—-以相同的方式处理不同的类型 —-只能显示指定具体的类型,无法自动推导 声明的泛指类型T可以出现在类模板的任意地方 以下非c++的规定,为工程建议: 1.泛型编程的思想可以应用于类
—-在类声明前使用template进行标识
—-用于说明类中使用的泛指类型T
templat<typename T>
class Operator
{
public:
T funv(T a)
{
}
};
3.类模板的应用
—-使用具体类型operator<int> op1;
operator<string> op2;
int i = op1.op(1,2);
string s = op2.op("DT","Software")
4.编译器如何处理类模板
编译器对类模板的处理方式和函数模板相同
—-从类模板通过类型产生不同的类
—-在声明的地方对类模板代码本身进行编译
—-在使用的地方对参数替换后的代码进行编译#include <iostream>
#include <string>
using namespace std;
/*重载string的相减操作*/
string operator -(string l, string r)
{
return "minus";
}
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 muliply(T& a, T& b)
{
return a * b;
}
T divide(T& a, T& b)
{
return a / b;
}
};
int main()
{
Operator<int> op1;
int a = 1;
int b = 2;
cout << op1.add(a,b) << endl;
string c = "D.T";
string d = " software";
Operator<string> op2;
cout << op2.add(c,d) << endl;
cout << op2.minus(c, d) << endl; //使用重载了的全局函数
return 0;
}
5.类模板的工程应用
—-类模板必须定义在头文件中
—-类模板不能分开实现在不同的文件中
—-类模板外部定义的成员函数需要加上模板<>声明#ifndef _TEST_H_
#define _TEST_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;
}
template <typename T>
T Operator<T>::minus(T a,T b)
{
return a - b;
}
template <typename T>
T Operator<T>::multiply(T a,T b)
{
return a * b;
}
template <typename T>
T Operator<T>::divide(T a,T b)
{
return a / b;
}
#endif
#include <iostream>
#include <string>
#include "test.h"
using namespace std;
string operator-(string& l, string& r)
{
return "Minus";
}
int main()
{
Operator<int> op1;
cout << op1.add(1, 2) << endl;
cout << op1.minus(1, 2) << endl;
cout << op1.multiply(2, 2) << endl;
cout << op1.divide(2, 2) << endl;
return 0;
}
小结
2.类模板以相同的方式处理不同类型的数据
3.类模板非常适合于编写数据结构相关的代码
4.类模板在使用时只能显示指定类型
