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

1

6

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.

Gelasias answered 14/4, 2016 at 19:56 Comment(0)
B
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.

Beverleybeverlie answered 14/4, 2016 at 20:52 Comment(2)
Thanks for your response. I currently have a work-around that is template<T> void foo(MatrixBase<Vec<T>>), 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.Gelasias
I think your followup comment is addressed hereUncovenanted

© 2022 - 2024 — McMap. All rights reserved.