Eigen 提供的模板指南建议使用 Eigen::MatrixBase 隐式推导函数的模板参数。在此示例中,我想传递一个表达式:
#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;
}
输出错误:
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);
是否有更通用的 Eigen::MatrixBase 形式可以扩展到接受表达式?
最佳答案
您必须使用两个模板参数并使输入引用引用 const
类型。问题是乘积运算符将返回一个 const
值。
像这样
template <typename U, typename V>
void eval(const Eigen::MatrixBase<U>& in, Eigen::MatrixBase<V>& out)
{
out.array() = in.array() + 1;
}
关于c++ - 泛化特征类型的输入参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69318119/