1
votes

I know for a fact that if I wanted to create a function that might or might not need to accept an Eigen dynamic double matrix, I need to define an empty dynamic matrix, say, somewhere before my function header is defined.

file.h

Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> EMPTY(0,0);

void myFunction(Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& inputMatrix); 
void myFunction(Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& inputMatrix=EMPTY);

file.cpp

void myFunction(Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& inputMatrix) {
     // do something
}

However the reality is, i'm currently working with a templated class and a function in this class has an Eigen matrix as optional parameter. Something like this...

myClass.h

template<typename Number>
class myClass {
    void myFunction(Eigen::Matrix<Number, Eigen::Dynamic, Eigen::Dynamic>& inputMatrix);
};

#include "myClass.tpp"

I've included the implementation of this templated class in a separate tpp file so I can hopefully have multiple function declarations. How can I then in this case make my inputMatrix a optional parameter? I've tried to declare the empty matrix above the class definition but I need the template typename for it to work.

1

1 Answers

1
votes

For this case, you'd better create two methods. One with a real parameter and one without parameter with the parametrized call inside. Something like this:

template<typename Number>
class myClass {
    void myFunction(Eigen::Matrix<Number, Eigen::Dynamic, Eigen::Dynamic>& inputMatrix);
    void myFunction()
    {
        myFunction(EMPTY);
    }
};

Usually, overloaded methods are easier to understand and maintain.