Search code examples
c++templateseigeneigen3

Eigen: Default type for MatrixBase in template function?


Suppose i have some function that can take optional argument of template type.

template<typename Scalar = int>
void foo(Scalar *out = NULL)
{
    std::cout << "HI!" << std::endl;
    if(out != NULL)
        *out = 42;
}

float x = 10;
foo(&x);//Call with optional argument
foo();//Call without optional argument

Of course compiler cannot deduce type of optional argument from call without optional argument, but we can help it by specifying default template argument

template<typename Scalar = int>

Suppose now i have real world example with Eigen

template</*some template args*/, typename Derived>
void solve(/*some args*/, std::vector<Eigen::MatrixBase<Derived>> *variablePath)

My question is - how to specify some default type for Derived? For example i want to make default type of variablePath to be std::vector<Eigen::MatrixXf> *

Of course I can use some common template argument instead of Eigen::MatrixBase<Derived> for example

template</*some template args*/, typename Matrix = Eigen::MatrixXf>
void solve(/*some args*/, std::vector<Matrix> *variablePath)

But i think it's quite dirty

PS Sorry for my English


Solution

  • I guess you also want to default variablePath to nullptr, so just write an overload without the optional argument:

    template</*some template args*/, typename MatType>
    void solve(/*some args*/, std::vector<MatType> *variablePath);
    
    template</*some template args*/>
    void solve(/*some args*/) {
      std::vector<MatrixXf> *nullvector = nullptr;
      solve(/*some args*/, nullvector);
    }