Re: [eigen] Overloading componentwise binary operators for vectors

[ Thread Index | Date Index | More lists.tuxfamily.org/eigen Archives ]



Here is a simple but complete example of what I want, which I hope to be free of syntaxic errors.
I does not compile because I am not sure of what I am doing with CwiseBinaryOp.

Feel free to tell me if it is not sufficient for you.

Best,

Cédric


----- Mail original -----
> De: "Marc Glisse" <marc.glisse@xxxxxxxx>
> À: eigen@xxxxxxxxxxxxxxxxxxx
> Envoyé: Vendredi 2 Octobre 2015 23:07:04
> Objet: Re: [eigen] Overloading componentwise binary operators for vectors
> 
> On Fri, 2 Oct 2015, Cedric Doucet wrote:
> 
> > Of course, there's a constructor:
> >
> > template<typename ScalarType>
> > Vector<ScalarType>::Vector<ScalarType>(std::size_t size)
>                              ^^^^^^^^^^^^
> you can omit that part.
> 
> > : wrapped_(size)
> > {}
> >
> > It does not work because I get an error message:
> >
> > erreur: ambiguous overload for ‘operator+’ (operand types are
> > ‘Vector<double>’ and ‘Vector<double>’)
> > CPPUNIT_ASSERT_EQUAL(sum, left+right);
> 
> Sorry, it is impossible to debug random pieces of incomplete code. This is
> general advice, to get help, you need to give people a way to easily
> reproduce the error, which means the full program (preferably minimized).
> 
> --
> Marc Glisse
> 
> 
> 

#include "Vector.hpp"

int main()
{
  Vector lhs(3);
  Vector rhs(3);

  lhs(0) = lhs(1) = lhs(2) = 1;
  rhs(0) = rhs(1) = rhs(2) = 2;

  //Vector sum(classical_sum(lhs,rhs));
  Vector sum(3);
  sum = lhs+rhs;
}
#include <Eigen/Core>
#include <Eigen/Dense>

// forward declarations
class Vector;

typedef Eigen::Matrix<double,Eigen::Dynamic,1> WrappedType;
typedef Eigen::internal::scalar_sum_op<double> SumOperator;
typedef Eigen::CwiseBinaryOp<SumOperator,Vector,Vector> Sum;

Vector 
classical_sum(Vector const & lhs, Vector const & rhs);

Sum
operator+(Vector const & lhs, Vector const & rhs);

// Vector class definition
class Vector
{
    friend Vector 
    classical_sum(Vector const & lhs, Vector const & rhs);

    friend Sum
    operator+(Vector const & lhs, Vector const & rhs);


    public:
      
      Vector(Vector const & copy)
      : wrapped_(copy.wrapped_)
      {}

      Vector(std::size_t const size)
      : wrapped_(size)
      {}

      double & 
      operator()(std::size_t const index)
      { return wrapped_(index); }

      Vector & operator=(Sum const & result)
      { 
        wrapped_ = result; 
        return *this; 
      }

    private:
      WrappedType wrapped_;
};

Vector 
classical_sum(Vector const & lhs, Vector const & rhs)
{ return lhs.wrapped_ + rhs.wrapped_; }

Sum
operator+(Vector const & lhs, Vector const & rhs)
{ return lhs.wrapped_ + rhs.wrapped_; }



Mail converted by MHonArc 2.6.19+ http://listengine.tuxfamily.org/