The template guide provided by Eigen recommends using Eigen::MatrixBase to implicitly deduce template parameters to functions. In this example I want to pass an expression:
#include <iostream>
#include "Eigen/Dense"
template <typename D>
void eval(Eigen::MatrixBase<D>& in, Eigen::MatrixBase<D>& out)
{
out.array() = in.array() 1;
}
int main()
{
Eigen::MatrixXd A(2,2);
A(0,0) = 2;
A(1,1) = 1;
Eigen::VectorXd B(2);
B(1) = 1;
std::cout << A << ", " << B << std::endl;
Eigen::VectorXd res(2);
eval(A*B, res);
std::cout << res << std::endl;
}
Which outputs an error:
EigenTest.cpp: In function ‘int main()’:
EigenTest.cpp:21:18: error: no matching function for call to ‘eval(const Eigen::Product<Eigen::Matrix<double, -1, -1>, Eigen::Matrix<double, -1, 1>, 0>, Eigen::VectorXd&)’
21 | eval(A*B, res);
Is there a more general form of Eigen::MatrixBase that extends to accepting expressions?
CodePudding user response:
You have to use two template parameters and make the input reference refer to a const
type. The issue is that the product operator will return a const
.
Like this
template <typename U, typename V>
void eval(const Eigen::MatrixBase<U>& in, Eigen::MatrixBase<V>& out)
{
out.array() = in.array() 1;
}