This forum has been archived. All content is frozen. Please use KDE Discuss instead.

Function overloading with MatrixBase of different dimensions

Tags: None
(comma "," separated)
erang
Registered Member
Posts
2
Karma
0
Hi,

I would like to create the following two overloads for an OpenGL helper function:

void GLVertex(const Eigen::Vector2f &vec) { glVertex2f(vec.x(),vec.y()); }
void GLVertex(const Eigen::Vector3f &vec) { glVertex3f(vec.x(),vec.y(),vec.z()); }

I quickly discovered that calling e.g. GLVertex(a+b) doesn't work because the type of a+b is a CwiseBinaryOp.
I understand that I should instead be defining these functions as receiving MatrixBase<Derived>. But how can I write these two functions using MatrixBase<Derived> but still let the compiler figure out which one to call??

Thank you
jitseniesen
Registered Member
Posts
204
Karma
2
You can use a helper struct with a default template argument and partial specialization to choose between the different functions:
Code: Select all
template <typename Derived, int RowsAtCompileTime = Derived::RowsAtCompileTime> struct GLVertex_impl;

template <typename Derived> struct GLVertex_impl<Derived, 2>
{
  static void run(const Eigen::MatrixBase<Derived> &vec) { glVertex2f(vec.x(),vec.y()); }
};
 
template <typename Derived> struct GLVertex_impl<Derived, 3>
{
  static void run(const Eigen::MatrixBase<Derived> &vec) { glVertex3f(vec.x(),vec.y(),vec.z()); }
};
 
template <typename Derived> void GLVertex(const Eigen::MatrixBase<Derived> &vec) { GLVertex_impl<Derived>::run(vec); }
I think boost::enable_if can also be used for this, but I don't have experience with it.

A different approach is to always evaluate the expression. The .eval() member function takes an expression (like a CwiseBinaryOp) and evaluates it into a Matrix.
Code: Select all
void GLVertex_impl(const Eigen::Vector2f &vec) { glVertex2f(vec.x(),vec.y()); }
void GLVertex_impl(const Eigen::Vector3f &vec) { glVertex3f(vec.x(),vec.y(),vec.z()); }

template <typename Derived> void GLVertex(const Eigen::MatrixBase<Derived> &vec) { GLVertex_impl(vec.eval()); }
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS
You can also have a look at the "unsupported/Eigen/OpenGLSupport" file, to see how we dealt with that issue. This file contains many wrappers to OpenGL functions.
erang
Registered Member
Posts
2
Karma
0
Thanks. Too bad it requires such awkward wrappers, but glad to see that there are some ready-made OpenGL wrappers available for my use.


Bookmarks



Who is online

Registered users: Bing [Bot], Google [Bot], Yahoo [Bot]