简体   繁体   English

使用DenseBase的模板化函数中的C ++本征块操作

[英]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. 但是当rr.segment(1,2)作为参数传递给函数时,最后一行中的operator-不会编译。 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(). 我知道问题在于,在testFunc()中,cc.segment被视为通用DenseBase对象,尽管针对特定的类.block()实现了该对象,但尚未实现该操作符。

You can tell Eigen to use the actual type encapsulated by the DenseBase class by writing c.derived() and r.derived() . 您可以通过编写c.derived()r.derived()来告诉Eigen使用DenseBase类封装的实际类型。

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: 不相关:代替R*Vector2d::Ones()编写Vector2d::Constant(R) ,并且如果整个表达式是按元素进行操作,则无论如何都应在Array域中工作:

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 ) (如果您通过ArrayBase而不是MatrixBaseDenseBase则可以忽略所有.derived().array()

Also, the .noalias() is only necessary if there are matrix products involved. 同样,仅在涉及矩阵乘积的情况下才需要.noalias()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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