在特征2库中使用linearRegression时,模板参数推导/替换失败



我在现有的C++代码库中工作,在调用函数时遇到问题。

我正在尝试使用代码库中已有的旧Eigen库中的线性回归函数,您可以在这里看到源代码,但下面是相关声明。

template<typename VectorType>
void linearRegression(int numPoints,
VectorType **points,
VectorType *result,
int funcOfOthers )
{ ... }

以下是我的代码的匿名副本:

// MyClass has member variable int maxIdx = 5
void MyClass::myFunction()
{
Eigen::Vector2d points[maxIdx];
Eigen::Vector2d coeffs;
for(int i = 0; i < maxIdx; i++)
{
points[i] = Eigen::Vector2d(data->mydata[i].x, data->mydata[i].y);
}
Eigen::linearRegression( maxIdx, &points, &coeffs, 1 );
// do more stuff with coeffs
}

这是我在尝试编译时收到的错误消息:

myfile.cpp:803:67: error: no matching function for call to 'linearRegression(int, Eigen::Vector2d (*)[((MyClass*)this)->MyClass::maxIdx], Eigen::Vector2d*, int)'
Eigen::linearRegression( maxIdx, &points, &coeffs, 1 );
^
myfile.cpp:803:67: note: candidate is:
In file included from [redacted]:
lib/Eigen/src/Eigen2Support/LeastSquares.h:85:6: note: template<class VectorType> void Eigen::linearRegression(int, VectorType**, VectorType*, int)
void linearRegression(int numPoints,
^
lib/Eigen/src/Eigen2Support/LeastSquares.h:85:6: note:   template argument deduction/substitution failed:
myfile.cpp:803:67: note:   mismatched types 'VectorType*' and 'Eigen::Vector2d [((MyClass*)this)->MyClass::maxIdx] {aka Eigen::Matrix<double, 2, 1> [((MyClass*)this)->MyClass::maxIdx]}'

这几乎是库源代码中示例代码的精确副本,所以我有点不知道如何修复它。我对模板不是很熟悉,所以类型错误可能与此有关?

根据源的(与他们的示例中所写的不同(,points应该是指向点的指针数组。也就是说,

Eigen::Vector2d *points[maxIdx];

所以,

Eigen::Vector2d points[maxIdx];
Eigen::Vector2d *point_ptrs[maxIdx];
for(int i = 0; i < maxIdx; i++)
point_ptrs[i] = &points[i];
...
Eigen::linearRegression(maxIdx, point_ptrs, &coeffs, 1);

这对Vector2d来说似乎很愚蠢,但可能是为不好复制的巨大矢量设计的。

为了抓住@numzero的答案,编译了该代码,但当我试图执行它时遇到了运行时崩溃。看起来第二个参数需要指向指针数组中的第一个索引。这个答案解释了发生了什么,以及它在运行时失败的时候,即使它已经编译了。

以下是最终对我有效的方法:

Eigen::Vector2d points[numPoints];
Eigen::Vector2d* point_ptrs[numPoints];
Eigen::Vector2d coeffs;
for(int i = 0; i < numPoints; i++)
{
points[i] = Eigen::Vector2d(data->mydata[i].x, data->mydata[i].y);
point_ptrs[i] = &points[i];
}
Eigen::linearRegression( maxIdx, &(point_ptrs[0]), &coeffs, 1 );

最新更新