以 cv::P oint_<T> 作为参数的模板函数无法编译

template function taking cv::Point_<T> as parameter won't compile

本文关键字:参数 函数 编译 gt oint cv lt      更新时间:2023-10-16

我正在尝试编写一个通用函数来序列化以字符串std::vector<cv::Point_<T>>,我希望它适用于cv::Point2icv::Point2f(两者都是具有特定 T 的cv::Point_<T>的类型定义)。

该函数如下所示:

template<typename T>
int SVIniFile::write(const std::string& section,
const std::string& key, 
std::vector<cv::Point_<T>>& points)
{
std::ostringstream os;
if (points.empty())
{
return SUCCESS;
}
for (size_t j = 0; j < points.size(); j++)
{
os << points[j].x << " " << points[j].y;
if (j < points.size() - 1)
{
os << " ";
}
}
write(section, key, os.str()); // do the writing of os.str() in the right `section` at `key`
return SUCCESS; // function that writes a string into an ini file
}

尝试编译此内容会引发"无法识别的模板声明/定义"错误。调查错误(完整的编译器输出如下),我发现了这个问题,但似乎与我的情况无关,以及这个问题,我不明白答案。

我对模板编程非常陌生,我怀疑错误是由于我将本身是其中一个参数的模板参数的类型用作模板参数这一事实引起的。谁能指出我正确的方向,并可能扩展一下为什么编译器不能构建它?


这是编译器在包含我的标头的每个文件中作为错误输出生成的:

1>svinifile.h(640):错误 C4430:缺少类型说明符 - 假定为 int。 注意:C++不支持 default-int 1>svinifile.h(640):错误 C2988:无法识别的模板声明/定义 1>svinifile.h(640):错误 C2143:语法错误:在"&"之前缺少",">

第 640 行是我上面显示的函数定义中紧随template<typename T>之后的那行。

为了

明确起见,cv::Point_<T>types.hpp中定义的 OpenCV 的 2D 点类型为:

namespace cv
{    
// ...
template<typename _Tp> class Point_
{
public:
typedef _Tp value_type;
//! default constructor
Point_();
Point_(_Tp _x, _Tp _y);
Point_(const Point_& pt);
Point_(Point_&& pt) CV_NOEXCEPT;
Point_(const Size_<_Tp>& sz);
Point_(const Vec<_Tp, 2>& v);
Point_& operator = (const Point_& pt);
Point_& operator = (Point_&& pt) CV_NOEXCEPT;
//! conversion to another data type
template<typename _Tp2> operator Point_<_Tp2>() const;
//! conversion to the old-style C structures
operator Vec<_Tp, 2>() const;
//! dot product
_Tp dot(const Point_& pt) const;
//! dot product computed in double-precision arithmetics
double ddot(const Point_& pt) const;
//! cross-product
double cross(const Point_& pt) const;
//! checks whether the point is inside the specified rectangle
bool inside(const Rect_<_Tp>& r) const;
_Tp x; //!< x coordinate of the point
_Tp y; //!< y coordinate of the point
};
typedef Point_<int> Point2i;
typedef Point_<int64> Point2l;
typedef Point_<float> Point2f;
typedef Point_<double> Point2d;
typedef Point2i Point;
}

由于显示的代码没有任何问题,因此问题一定出在您尚未显示的某些代码上。这可能是非常简单的事情,例如丢失或无序 #include。

您应该尝试创建一个最小、完整和可验证的示例。您可能会在执行此操作时发现问题。

例如,这在VS 2017上编译得很好:

#include <vector>
namespace cv {
template<typename _Tp> class Point_ {};
typedef Point_<int> Point2i;
}
class SVIniFile {
public:
template<typename T>
int write(
const std::string& section,
const std::string& key,
std::vector<cv::Point_<T>>& points);
};
template<typename T>
int SVIniFile::write(
const std::string& section,
const std::string& key,
std::vector<cv::Point_<T>>& points) {
return 0;
}
int main() {
SVIniFile svIniFile;
std::vector<cv::Point2i> points;
svIniFile.write("abc", "def", points);
return 0;
}