本征库:将块引用传递给模板函数时出现编译器错误
Eigen Library: Compiler error when passing Block reference to templated function
我在尝试使用 Eigen 引用的参数调用模板函数时遇到编译错误。
例如,考虑以下简化示例:
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));
编译器抱怨我试图用一个按值传递的对象实例化一个非常量引用(如果我对以下内容的理解是正确的):
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> >’
如果我尝试将 fcn 的参数声明为 const
,那么当我尝试在函数内部修改它时会出现错误。
我发现解决此问题的唯一解决方案是将函数的参数声明为 const &
,然后使用 const_cast
到 "remove the const qualifier"在函数内部访问 M
时。
但这是 hacky,我使代码非常混乱。我错过了这个问题的一些明显解决方案吗?任何帮助,将不胜感激。
谢谢!
T
这是因为在 c++ 中,您不能将临时对象(这里是 .block()
返回的代理对象)绑定到 non-const 引用。解决方法是命名:
auto A_block = A.block<9,6>(10,10);
fcn(A_block);
我在尝试使用 Eigen 引用的参数调用模板函数时遇到编译错误。
例如,考虑以下简化示例:
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));
编译器抱怨我试图用一个按值传递的对象实例化一个非常量引用(如果我对以下内容的理解是正确的):
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> >’
如果我尝试将 fcn 的参数声明为 const
,那么当我尝试在函数内部修改它时会出现错误。
我发现解决此问题的唯一解决方案是将函数的参数声明为 const &
,然后使用 const_cast
到 "remove the const qualifier"在函数内部访问 M
时。
但这是 hacky,我使代码非常混乱。我错过了这个问题的一些明显解决方案吗?任何帮助,将不胜感激。 谢谢!
T
这是因为在 c++ 中,您不能将临时对象(这里是 .block()
返回的代理对象)绑定到 non-const 引用。解决方法是命名:
auto A_block = A.block<9,6>(10,10);
fcn(A_block);