Search code examples
c++templateseigeneigen3

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


Here is a function I would like to write:

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)
}

In particular I would like to be able to call foo without passing in a type parameter to the template, but instead have the function infer the type by the argument. When I run this code I get the error that

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

This function works fine if I pass in the type to the function call, such as foo<double>(v). I also know the type T can be inferred if the signature of foo is

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

but that is not a good way of passing Eigen vectors by reference as it destroys the benefits of expression templates.

I also can not use the MatrixBase method of passing by reference

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

because I want to be sure the vector being passed in is of type T, and I don't know how to ensure that with this method.

Is there a way of using Ref<> in a templated function like this where it will infer the type T? All help is appreciated.


Solution

  • For template code use the MatrixBase approach, and to control the scalar type, then use either a static assertion or a enable_if construct. Use typename Derived::Scalar to get the scalar type of the expression.