您的位置:首页 > 编程语言 > C语言/C++

Cpp-泛型编程基础

2018-01-27 17:26 225 查看

Cpp-泛型编程基础

哇,很久没有写cpp了,写得太挫了,主要是。emm,好像数据结构作业是实现线程池,趁此机会好好学一遍cpp吧,不要再吹水了。只希望。
C++是一门很强大的语言,泛型编程一般来说可望而不可及,今天来啃一下这小基础吧。

函数重载

假设要比较两个数的值,我们可以使用两个函数进行重载:
int compare(const int&a, const int&b)
{
if (a == b) return 0;
return a>b ? 1 : -1;
}
int compare(const double&a, const double&b)
{
if (a == b) return 0;
return a > b ? 1 : -1;
}
两个函数基本相同,唯一不同的是函数的参数,但是这种比较麻烦。也比较容易出错。
所以对于不同类型都需要用这个函数,我们就产生了这个模板。

模板的定义

template <typename T>
int compare(const T &v1, const T &v2)
{
if (v1 < v2) return 1;
else return 0;
}
模板的定义以关键字 template开始,后面接着模板参数,模板的形参是用尖括号或者多个模板形参,形参之间用逗号进行分割。
使用函数模板
使用函数模板的时候,编译器推断是哪个模板实参绑定到模板形参。一旦编译器确定了实际的模板实参,也就是实例化了函数模板的实例

std::cout << compare(1, -1)<<std::endl;

inline函数模板

函数模板可以用非函数模板一样的声明为Inline,说明符号放在模板形参表之后,返回类型之前,不能放在关键字template之前。
template <typename T> inline T min(const T&a, const T&b)
{
return a > b ? b : a;
}

定义类模板

当我们定义类的模板的时候同使用函数模板是一样的。
定义一个Point类,可能是2D,也有可能是3D,所以需要类模板,第一种定义是3d的Point

template<class type>
class Point3d
{
public:
Point3d(type x = 0.0, type y = 0.0, type z = 0.0) :_x(x), _y(y), _z(z){}
type x()
{
return _x;
}
void x(type xval)
{
_x = xval;
}
private:
type _x;
type _y;
type _z;
};
或者我们也可以变成
template <class type,int dim>
class Point
{
public:
Point();
Point(type coords[dim])
{
for (int index = 0; index < dim; index++)
{
_coords[index] = coords[index];
}
}
type& operator[](int index)
{
assert(index < dim&&index >= 0);
return _coords[index];
}
type operator[](int index) const
{
assert(index < dim&&index >= 0);
return _coords[index];
}
private:
type _coords[dim];
};
这样就可以,然后直接声明这个就可以进行调用:
Point<int, 3> point;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: