C语言中Generic的实现

时间:2019-11-20 12:35:29

标签: c++ opencv

我想实现一个通用方法,该方法将采用Points的向量(Point可以是整数,浮点型或双精度型)并返回矩形。 (我正在使用OpenCV)。

通过阅读http://www.cplusplus.com/doc/oldtutorial/templates/中的c ++泛型在线教程 我已经实现了上述方法,但是却遇到了编译时错误。

  

Error: Error LNK2001 unresolved external symbol "public: static class cv::Rect_<int> __cdecl getRect<int>(class std::vector<class cv::Point_<int>,class std::allocator<class cv::Point_<int> > >)" (??$getRect@H@CvUtil@i2v@@SA?AV?$Rect_@H@cv@@V?$vector@V?$Point_@H@cv@@V?$allocator@V?$Point_@H@cv@@@std@@@std@@@Z)

我无法理解此错误。 有人可以向我解释这里可能出什么问题吗?

下面是我的实现的代码段。

template<typename T>
struct XCoordSortX {
    bool operator() (cv::Point_<T> pt1, cv::Point_<T> pt2) { return (pt1.x < pt2.x); }
};
template<typename T2>
struct XCoordSortY {
    bool operator() (cv::Point_<T2> pt1, cv::Point_<T2> pt2) { return (pt1.y < pt2.y); }
};

template<class T3>
cv::Rect getRect(const std::vector<cv::Point_<T3>> points)
{
    cv::Rect rect;
    std::vector<cv::Point_<T3>> tempPoints(points);
    XCoordSortX<T3> sortX;
    std::sort(tempPoints.begin(), tempPoints.end(), sortX); // sorting by x coordinate

    rect.x = tempPoints[0].x; // setting top left point as lowest x
    rect.width = tempPoints[tempPoints.size() - 1].x - tempPoints[0].x; // width will be diff between largest and smallest

    XCoordSortY<T3> sortY;
    std::sort(tempPoints.begin(), tempPoints.end(), sortY);
    rect.y = tempPoints[0].y; // setting top left point as lowest y
    rect.height = tempPoints[tempPoints.size() - 1].y - tempPoints[0].y;// height will be diff between largest and smallest
    return rect;
}

int main()
{
    std::vector<cv::Point> pointVec;
    pointVec.push_back(cv::Point(2, 3));   // cv::Point is cv::Point_<int> type
    pointVec.push_back(cv::Point(2, 10));
    pointVec.push_back(cv::Point(10, 3));
    pointVec.push_back(cv::Point(12, 5));

    pointVec.push_back(cv::Point(40, 50));
    pointVec.push_back(cv::Point(40 ,100));
    pointVec.push_back(cv::Point(100, 40));
    pointVec.push_back(cv::Point(50,50));

    cv::Rect newRoi = getRect<int>(pointVec); // Error here
}

0 个答案:

没有答案