对模板化函数中的通用特征矩阵使用 Ref<>

Using Ref<> for generic Eigen matrices in a templated function

本文关键字:Ref lt gt 函数 特征      更新时间:2023-10-16

这里有一个我想写的函数:

template<typename NumType> using Vec = Eigen::Matrix<NumType, Eigen::Dynamic, 1>;

template<typename T>
void foo(Eigen::Ref<Vec<T>> p)
{
  // fill p with things
}
void main()
{
  Vec<double> v(2);
  foo(v)
}

特别是,我希望能够在不向模板传递类型参数的情况下调用foo,而是让函数通过参数推断类型。当我运行此代码时,我得到的错误

No matching function call to 'foo'
Candidate template ignored: could not match 'Ref' against 'Matrix'

如果我将类型传递给函数调用,例如foo<double>(v),则此函数可以正常工作。我还知道如果foo的签名是,则可以推断出类型T

template<typename T>
void foo(Vec<T> & p)

但这不是通过引用传递特征向量的好方法,因为它破坏了表达模板的好处。

我也不能使用通过参考的MatrixBase方法

template<typename Derived>
void foo(Eigen::MatrixBase<Derived>& p)

因为我想确保传入的向量是T类型的,而我不知道如何用这个方法来确保这一点。

有没有一种方法可以在像这样的模板函数中使用Ref<>来推断类型T?感谢所有的帮助。

对于模板代码,请使用MatrixBase方法,并且要控制标量类型,请使用静态断言或enable_if构造。使用typename Derived::Scalar获取表达式的标量类型。