如何覆盖C ++模板子类中的转换运算符?

时间:2017-02-12 21:22:42

标签: c++ opencv type-conversion operator-overloading operators

如何覆盖C ++模板子类中的转换运算符? 例如,我尝试从openCv实现Rect_ template类的子类:

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
    {
        ... ?
    }
};

提前致谢。

1 个答案:

答案 0 :(得分:0)

您可以创建非显式构造函数以从父实例构造类的实例:

ColorRect_(const cv::Rect_<_Tp>& other) {...};

它的工作方式与转换运算符相同。