2017-02-12 81 views
0

如何覆蓋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 
    { 
     ... ? 
    } 
}; 

在此先感謝。

+4

無關,但以下劃線開頭的標識符後面緊跟着一個大寫字母,它們在C++中保留。 – rustyx

回答

0

您可以創建非顯式構造函數,父實例構造你的類的實例:

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

它的工作方式是轉換操作符相同。