5

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.

jbcolli2
  • 113
  • 1
  • 4

1 Answers1

2

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.

ggael
  • 28,425
  • 2
  • 65
  • 71
  • 1
    Thanks for your response. I currently have a work-around that is `template void foo(MatrixBase>)`, however this does not work if I pass in a vector of fixed size. Can you explain why it can't convert a fixed sized vector to a dynamically sized vector? I'm mostly just trying to understand how it all works, but I also like this method because it does not allow my user to pass in a matrix when I want a vector. I can of course check to be sure the parameter is a vector, but this seems more elegant. – jbcolli2 Apr 15 '16 at 14:39
  • I think your followup comment is addressed [here](https://stackoverflow.com/questions/74194702/non-const-reference-of-eigen-matrix-only-bind-with-dynamic-types-and-not-with-no) – ofloveandhate Jul 07 '23 at 22:11