C ++ Eigen: why one add-assign but not add for asDiagonal () method
I noticed unexpected behavior in Eigen:
int n=10; //value is irrelevant
Eigen::MatrixXd A(n);
Eigen::VectorXd v(n);
//works:
Eigen::MatrixXd B = A;
B += v.asDiagonal();
//error:
Eigen::MatrixXd C = A + v.asDiagonal();
In the second case, the compiler complains that there is no suitable one operator+
available using MatrixXd
and a DiagonalWrapper<...>
. (The same is true for other operators).
Is this intended? And if so, is there a neat way around the two-line alternative (assign first and then subtract)?
source to share
You could just write the + operator yourself, like
namespace Eigen {
template <typename OtherMatrix>
auto operator+(MatrixXd lhs, OtherMatrix&& rhs)
{
return lhs += rhs;
}
}
Note that this will force the argument to be evaluated lhs
, in particular, whatever it might cost to construct a MatrixXd
, which might be the reason the authors of Eigen omitted it.
source to share