简体   繁体   中英

c++ eigen block operations in templated functions taking DenseBase

This works

Vector2d a(1,2);
VectorXd cc(10);
cc << 1.0, 2.0, 3, 4, 5, 6, 7, 8, 9;
VectorXd rr(10);
rr << 1.0, 2.0, 3, 4, 5, 6, 7, 8, 9;
int R(10);
Vector2d G(Vector2d::Zero());


G.noalias() -= cc.segment(4, 2) + 
               (rr.segment(1, 2) - R*Vector2d::Ones()).cwiseQuotient(a); // OK here

but when rr.segment(1, 2) is passed as argument to a function, the operator- in the last line doesn't compile. The problem occurs in this code

template <typename DerivedA, typename DerivedB, typename DerivedC>
void testFunc(MatrixBase<DerivedA>& G, const DenseBase<DerivedB>& c, const DenseBase<DerivedC>& r)
{  
   Vector2d a(1,2);
   int R(10);
   G.noalias() -= c + (r - R*Vector2d::Ones()).cwiseQuotient(a);
};

VectorXd cc(10);
cc << 1.0, 2.0, 3, 4, 5, 6, 7, 8, 9;
VectorXd rr(10);
rr << 1.0, 2.0, 3, 4, 5, 6, 7, 8, 9;
Vector2d G(Vector2d::Zero());
testFunc(G, cc.segment(4, 2), rr.segment(1, 2)); // ERROR : no match for 'operator-'

I understand that the problem is in the fact that in testFunc(), cc.segment is seen as a general DenseBase object for which the operator- is not implemented, although it is implemented for the particular class .block().

You can tell Eigen to use the actual type encapsulated by the DenseBase class by writing c.derived() and r.derived() .

Unrelated: Instead of R*Vector2d::Ones() write Vector2d::Constant(R) , and if the entire expression is element-wise operations, you should work in the Array domain anyway:

template <typename DerivedA, typename DerivedB, typename DerivedC>
void testFunc(MatrixBase<DerivedA>& G, const DenseBase<DerivedB>& c, const DenseBase<DerivedC>& r)
{
   Array2d a(1,2);
   int R(10);
   G.array() -= c.derived().array() + (r.derived().array() - R)/a;
}

(You could leave out all .derived() and .array() if you passed ArrayBase instead of MatrixBase or DenseBase )

Also, the .noalias() is only necessary if there are matrix products involved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM