在Opencv 中使用了大量的template模板类,是由于图像的数据类型有8位、16位、32位,整形、float 型等多种类型,不可能为每种类型都定义相关类,因此引入了模板类的概念。
模板(Templates)使得我们可以生成通用的函数,这些函数能够接受任意数据类型的参数,可返回任意类型的值,而不需要对所有可能的数据类型进行函数重载。这在一定程度上实现了宏(macro)的作用。
它们的原型定义可以是下面两种中的任何一个:
template <class identifier> function_declaration;
template <typename identifier> function_declaration;
上面两种原型定义的不同之处在关键字class 或 typename的使用。它们实际是完全等价的,因为两种表达的意思和执行都一模一样。
以Opencv中的Size_模板类为例:
template<typename _Tp> class Size_
{
public:
typedef _Tp value_type;
//! various constructors不同的构造函数定义
Size_();
Size_(_Tp _width, _Tp _height);
Size_(const Size_& sz);
Size_(const Point_<_Tp>& pt);
Size_& operator = (const Size_& sz);
//! the area (width*height)
_Tp area() const;
//! true if empty
bool empty() const;
//! conversion of another data type.转化为另一种数据类型
template<typename _Tp2> operator Size_<_Tp2>() const;
_Tp width, height; // the width and the height 常用的属性,宽度和高度
};
上面 _Tp 就可以是任意的数据类型,比如Size_<int>,表示其类内部模板是int型,在这里_Tp就相当于是int 的宏定义