gpt4 book ai didi

c++ - 在 C++ 中使用 eigen3 进行继承和转换

转载 作者:行者123 更新时间:2023-11-28 07:31:10 25 4
gpt4 key购买 nike

我想扩展一个 eigen3 类型如下:

typedef Eigen::Matrix<unsigned char, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> CMatrixImgParent;

class CMatrixImg : public CMatrixImgParent
{
public:
CMatrixImg() : CMatrixImgParent() {}

int Dummy(const char *filename) const {};
};

然后用 eigen3 做一些算术。

CMatrixImg img1, img2, imgSum;
imgSum = img1 + img2;

但这不起作用,因为我使用 g++ 得到错误:

g++ -o bug.o -c -O2 -I/usr/include/eigen3 bug.cc
bug.cc: In function 'int main(int, char**)':
bug.cc:17:10: error: no match for 'operator=' (operand types are 'CMatrixImg' and 'const Eigen::CwiseBinaryOp<Eigen::internal::scalar_sum_op<unsigned char>, const Eigen::Matrix<unsigned char, -1, -1, 1>, const Eigen::Matrix<unsigned char, -1, -1, 1> >')
imgSum = img1 + img2;
^
bug.cc:17:10: note: candidate is:
bug.cc:5:7: note: CMatrixImg& CMatrixImg::operator=(const CMatrixImg&)
class CMatrixImg : public CMatrixImgParent
^
bug.cc:5:7: note: no known conversion for argument 1 from 'const Eigen::CwiseBinaryOp<Eigen::internal::scalar_sum_op<unsigned char>, const Eigen::Matrix<unsigned char, -1, -1, 1>, const Eigen::Matrix<unsigned char, -1, -1, 1> >' to 'const CMatrixImg&'
scons: *** [bug.o] Error 1
scons: building terminated because of errors.

Compilation exited abnormally with code 2 at Tue Jul 16 18:31:18

当然我可以通过像这样的显式转换来解决这个问题:

(*(CMatrixImgParent*)&imgSum) = img1 + img2;

但这很丑陋。

我可以在类定义中放置任何简单的代码来解决对这种类型转换的需求吗?

最佳答案

documentation for Eigen建议从 Eigen::Matrix 继承(在您的示例中本质上是 CMatrixImgParent)应该只是最后的手段,并且允许您添加的宏驱动方法Eigen::Matrix 的成员是首选:

Before inheriting from Matrix, be really, i mean REALLY sure that using EIGEN_MATRIX_PLUGIN is not what you really want (see previous section). If you just need to add few members to Matrix, this is the way to go.

宏观方法描述为:

In this section we will see how to add custom methods to MatrixBase. Since all expressions and matrix types inherit MatrixBase, adding a method to MatrixBase make it immediately available to all expressions ! A typical use case is, for instance, to make Eigen compatible with another API.

You certainly know that in C++ it is not possible to add methods to an existing class. So how that's possible ? Here the trick is to include in the declaration of MatrixBase a file defined by the preprocessor token EIGEN_MATRIXBASE_PLUGIN

他们举的例子是

class MatrixBase {
// methods ...
#ifdef EIGEN_MATRIXBASE_PLUGIN
#include EIGEN_MATRIXBASE_PLUGIN
#endif
};

因此,您似乎可以按照这种方法来定义您的 int Dummy(const char* filename) const 方法。如果你真的想从 Eigen::Matrix 继承,似乎你需要自己写一个赋值运算符,如 n.m.在评论中提到。

关于c++ - 在 C++ 中使用 eigen3 进行继承和转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17681139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com