如何覆盖C++模板子类中的转换运算符?
问题描述:
如何覆盖C++模板子类中的转换运算符? 例如,我试图从OpenCV的实现Rect_模板类的子类:如何覆盖C++模板子类中的转换运算符?
template<typename _Tp> class Rect_
{
public:
typedef _Tp value_type;
//! various constructors
Rect_();
Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height);
Rect_(const Rect_& r);
Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz);
Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2);
Rect_& operator = (const Rect_& r);
//! the top-left corner
Point_<_Tp> tl() const;
//! the bottom-right corner
Point_<_Tp> br() const;
//! size (width, height) of the rectangle
Size_<_Tp> size() const;
//! area (width*height) of the rectangle
_Tp area() const;
//! conversion to another data type
template<typename _Tp2> operator Rect_<_Tp2>() const;
//! checks whether the rectangle contains the point
bool contains(const Point_<_Tp>& pt) const;
_Tp x, y, width, height; //< the top-left corner, as well as width and height of the rectangle
};
我的子类ColorRect有额外的领域 - 颜色。我如何从父类中覆盖转换运算符?如果不可能,我可以给转换操作员打电话吗?我该怎么做?
template<typename _Tp> class ColorRect_ : public cv::Rect_<_Tp>
{
uchar color;
ColorRect_(): cv::Rect_() { color = NONE; }
ColorRect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height, uchar color) : cv::Rect_(_x, _y, _width, _height), color(color)
{
}
ColorRect_(const ColorRect_& r) : cv::Rect_(r), color(r.color) {}
ColorRect_& operator = (const ColorRect_& r)
{
cv::Rect_<_Tp>::operator=(r);
color = r.color;
return this;
}
template<typename _Tp2> operator ColorRect_<_Tp2>() const
{
... ?
}
};
在此先感谢。
答
您可以创建非显式构造函数,父实例构造你的类的实例:
ColorRect_(const cv::Rect_<_Tp>& other) {...};
它的工作方式是转换操作符相同。
无关,但以下划线开头的标识符后面紧跟着一个大写字母,它们在C++中保留。 – rustyx