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

时间:2016-04-14 19:56:24

标签: c++ templates eigen eigen3

这是我想写的一个函数:

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),则此函数可以正常工作。如果T的签名是

,我也知道可以推断类型foo
template<typename T>
void foo(Vec<T> & p)

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

我也不能使用通过引用传递的MatrixBase方法

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

因为我想确保传入的向量是T类型,并且我不知道如何使用此方法确保传输。

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

1 个答案:

答案 0 :(得分:2)

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

相关问题