Home > Enterprise >  C /Eigen - How to pass a general vector as parameter?
C /Eigen - How to pass a general vector as parameter?

Time:01-25

Using Eigen 3.4.0

I want to write a function general for any Eigen::Vector. e.g.

Eigen provides MatrixBase for any Eigen object, but I want to be explicit that this is a vector only function.

For example, I could write a general MatrixBase function as follows:

   template<Derived>
   typename MatrixBase<Derived>::PlainObject foo(MatrixBase<Derived>& M)
   { // N = operations on M
     // ...
     return N;
   }

I want something to the effect of:

   template<Derived>
   typename VectorBase<Derived>::PlainObject foo(VectorBase<Derived>& M);

I tried:

  template<Derived>
   Vector<typename Derived::Scalar, Dynamic> foo(Vector<typename Derived::Scalar>& M);

This doesn't work.

My current solution is to just template the function and make the template clear to use vectors only, but doesn't seem like the best practice.

   template<VectorX>
   VectorX foo(VectorX M);

CodePudding user response:

There is no VectorBase in the Eigen library. Eigen::Vector is just an alias for Eigen::Matrix:

template<typename Type , int Size>
using   Eigen::Vector = Matrix< Type, Size, 1 >

So, if you want your function to allow only Eigen::Vector, then simply take a Eigen::Vector function argument, but you will need template arguments to match Vector's template arguments, eg:

template<typename Type, int Size>
typename Eigen::Vector<Type,Size>::PlainObject foo(Eigen::Vector<Type,Size>& M);
  • Related