Reputation: 11733
I've subclassed Eigen::Vector2d for have some convenience methods that i don't will write here (like MyVec.randomize()
, MyVec.distanceWithThreshold()
, etc..).
But I'm facing with a error in conversion when I try to assign to a new vector some simple operation. Let's see my code:
#include <iostream>
#include "Eigen/Core"
class Vec2D : public Eigen::Vector2d {
public:
Vec2D() : Eigen::Vector2d() {};
Vec2D(double x, double y) : Eigen::Vector2d(x,y) {}
};
std::ostream& operator<< (std::ostream &out, Vec2D &cPoint) {
out << "(" << cPoint.x() << ", " << cPoint.y() << ")";
return out;
}
int main() {
// test with base class
Eigen::Vector2d A = Eigen::Vector2d(0,0);
Eigen::Vector2d B = Eigen::Vector2d(5,5);
Eigen::Vector2d C = A - B;
std::cout << C.x() << " " << C.y() << std::endl;
// test with my subclassed Vec2D
Vec2D _A,_B;
_A = Vec2D(0, 0);
_B = Vec2D(5, 5);
std::cout << _A-_B << std::endl; // my stream overload is not called
std::cout << _A << std::endl; // my stream overload is called
// now the problem
Vec2D dudeee = _A - _B; // if I comment this line, no error
std::cout << dudee << std::endl; // if I comment this line, no error
return 0;
}
and the error is:
test.cpp: In function 'int main()':
test.cpp:34: error: conversion from 'const Eigen::CwiseBinaryOp<Eigen::internal::scalar_difference_op<double>, const Eigen::Matrix<double, 2, 1, 0, 2, 1>, const Eigen::Matrix<double, 2, 1, 0, 2, 1> >' to non-scalar type 'Vec2D' requested
test.cpp:35: error: 'dudee' was not declared in this scope
I think (because of call on my stream operator overload) that in some way I have to overwrite the normal operators (+, - *, /) in Vec2D too saying in some way to allocate a new Vec2D object, but I don't know how to do. Some advice?
Upvotes: 0
Views: 1831
Reputation: 29205
Regarding the compilation error, in C++ constructors as well as assignment operators are not automatically inherited. See this doc. In particular you have to re-implement all constructors of the Matrix<> class, and add:
using Vector2d::operator=;
to forward assignment operators.
Regarding A-B, its type is a CwiseBinaryOp<...> expression. If you want it to be a Vec2D, then you have to cast it:
cout << Vec2D(A-B);
Finally, if your only purpose is to extend Eigen's API, then the best is to use Eigen's plugin plugin mechanism. The following plugins exist:
Upvotes: 2