我想扩展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;
但这非常丑陋。
有没有什么简单的代码可以放在类定义中来避免这种类型的转换?
发布于 2013-07-17 00:23:52
documentation for Eigen建议,从Eigen::Matrix
(在您的示例中本质上是CMatrixImgParent
)继承应该是最后的手段,并且首选的是允许您直接向Eigen::Matrix
添加成员的宏驱动方法:
在继承
之前,真的,我的意思是确定使用EIGEN_MATRIX_PLUGIN并不是你真正想要的(见上一节)。如果你只需要向Matrix中添加几个成员,这就是你要做的。
宏方法描述为:
在本节中,我们将了解如何向MatrixBase添加自定义方法。因为所有的表达式和矩阵类型都继承了MatrixBase,所以在MatrixBase中添加一个方法可以让它立即对所有的表达式可用!例如,一个典型的用例是使Eigen与另一个API兼容。
您当然知道,在C++中,不可能向现有类添加方法。那么这是怎么可能的呢?这里的诀窍是在MatrixBase的声明中包含一个由预处理器标记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。评论中提到的。
发布于 2013-07-17 00:30:41
向CMatrixImg
类添加来自CMatrixImgParent
的赋值操作符解决了类型转换问题:
class CMatrixImg : public CMatrixImgParent
{
public:
// Constructor
CMatrixImg() : CMatrixImgParent() {}
// This is needed for assignment of arithmetic results.
CMatrixImg& operator=(const CMatrixImgParent& Other) {
*((CMatrixImgParent*)this) = Other;
return *this;
}
int Dummy(const char *filename) const {};
};
但也可以参阅RyanMcK的答案,它可能更适合eigen3。
https://stackoverflow.com/questions/17681139
复制相似问题