c++ - 泛化特征类型的输入参数

标签 c++ eigen template-argument-deduction

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/

相关文章:

c++ - 具有 x、y、z 的点和具有 x()、y()、z() 的点的模板函数

c++ - 空派生优化

c++ - 使用 Eigen 创建简单矩阵?

c++ - 是否可以从 Eigen 中的 1 开始索引矩阵?

c++ - 有没有办法递归地使用类模板参数推导指南? (图灵完备了吗)

c++ - 为什么需要复制扣除候选作为单独的扣除指南?

c++ - SFINAE 仅启用从派生类到基类的强制转换运算符

c++ - 从 std::vector 中删除动态分配的对象

c++ - 使用空格分隔符从输入流中拆分字符串

c++ - std::copy 毫无异常(exception)地导致错误