[eigen] Expression templates and CwiseBinaryOp
• To: eigen@xxxxxxxxxxxxxxxxxxx
• Subject: [eigen] Expression templates and CwiseBinaryOp
• From: Cedric Doucet <cedric.doucet@xxxxxxxx>
• Date: Wed, 3 Aug 2016 15:12:35 +0200 (CEST)
• Thread-topic: Expression templates and CwiseBinaryOp

Hello,

I would like to understand how _expression_ templates work in Eigen.
I understood that the sum of two dynamical double vectors is performed by something which looks like this :

CwiseBinaryOp< internal::scalar_sum_op<double>, VectorXd const, VectorXd const > operator+(VectorXd const & lhs, VectorXd const & rhs);

I also understood how the difference of two vectors is implemented.

I have two questions.

1. How does the product of a vector by a scalar work?

I have noticed that CwiseBinaryOp< internal::scalar_product_op<double>, VectorXd const, VectorXd const > exists but I have the feeling that it is only designed to perform componentwise operations between two vectors.
Does it mean that the product of a vector by a scalar correspond to a unary operator, say CwiseUnaryOp< internal::scalar_product_op<double>, VectorXd const, VectorXd const >?

2. Can template expressions be built from mixed operations?

For example, in an _expression_ like x = u + 2 * v - w, is it true that these operations are performed in a nested way like this?

a. v-w leads to the construction of an instance of CwiseBinaryOp< internal::scalar_difference_op<double>, VectorXd const, VectorXd const > (alias E1)
b. 2 * v leads to the construction of an instance of CwiseUnaryOp< internal::scalar_product_op<double>, VectorXd const > (alias E2)
c. 2 * v + v- w leads to the construction of an instance of CwiseBinaryOp< internal::scalar_sum_op<double>, E1 const, E2 const > (alias E3)
d. u + 2 * v - w leads to the construction of an instance of CwiseBinaryOp< internal::scalar_sum_op<double>, VectorXd const, E3 const > (alias E4)
e. x = u + 2 * v -w calls the constructor VectorXd(E4 const &), or the overloading VectorXd & operator=(E4 const &), which evaluate the tree built from the previous steps.