I want to construct a class that contains several Eigen Matrices or Vectors. I want the objects to behave as mathematical vectors: therefore I want to overload +, - and *(by a scalar). I want to do very many linear combinations of these objects, so I would like to implement it in a way that it takes full advantage of Eigen and creates as few copies and temporaries as possible.
I usually follow the recommendations in What are the basic rules and idioms for operator overloading? but they require to pass some of the object by value rather than reference. Eigen "dislikes" when matrices are passed by value.
Below is my attempt (I overload only + for shortness) where I avoid passing by value in the overloading of + and instead I use the named return value optimization (NRVO):
template <int N> class myClass {
public:
Eigen::Matrix<double, N, N> mat = Eigen::Matrix<double, N, N>::Zero();
Eigen::Matrix<double, N, 1> vec = Eigen::Matrix<double, N, 1>::Zero();
public:
myClass(){}
myClass(Eigen::Matrix<double, N, N> & t_mat,Eigen::Matrix<double, N, 1> &t_vec) : mat (t_mat), vec(t_vec){ }
myClass(const myClass & other): mat(other.mat), vec(other.vec) {};
myClass& operator+=(const myClass& rhs){
mat += rhs.mat; vec += rhs.vec;
return *this;
}
public:
enum { NeedsToAlign = (sizeof(mat)%16)==0 || (sizeof(vec)%16)==0 };
EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF(NeedsToAlign)
};
template <int N> myClass<N>& operator+( const myClass<N>& lhs, const myClass<N>& rhs )
{
myClass<N> nrv( lhs );
nrv += rhs;
return nrv;
}
Is this the best solution? Fastest?
As a final short question: it would be nice to use Boost/operators (https://www.boost.org/doc/libs/1_54_0/libs/utility/operators.htm) to easily complete the set of operator overloading. Can I use that, or would that cause problems? I guess it will implement binary operations passing the first argument by value.