Reputation: 23
I am getting a compilation error when trying to call templated functions with arguments that are Eigen references.
For example, consider the following simplified example:
template <typename derived>
inline void fcn(Eigen::MatrixBase<derived> &M){
// ...
M.template block<3,3>(0,0) = something here
// ...
}
// I get compiler errors when trying to call this function as follows:
Eigen::MatrixXd A(100,100);
// call the above function with a Block as an argument
fcn(A.block<9,6>(10,10));
The compiler complains that I am trying to instantiate a non-const reference with an object passed by value (if my undersdanding of the following is correct):
error: invalid initialization of non-const reference of type ‘Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, -1, -1>, 9, 6, false> >&’ from an rvalue of type ‘Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, -1, -1>, 9, 6, false> >’
If I try to declare the argument of fcn as const
then I am getting an error when I try to modify it inside the function.
The only solution I've found to work to fix this issue is to declare the arument of the function to be a const &
, and then to use const_cast
to "remove the const qualifier" when accessing M
inside the function.
But this is hacky and I makes the code extremely messy. Am I missing some obvious solution to this problem? Any help would be appreciated. Thanks!
T
Upvotes: 2
Views: 1244
Reputation: 29255
This is because in c++ you cannot bind a temporary object (here the proxy object returned by .block()
) to a non-const reference. The solution is to name it:
auto A_block = A.block<9,6>(10,10);
fcn(A_block);
Upvotes: 4