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

Template Functions with MatrixBase as Parameter

Tags: None
(comma "," separated)
dubmarauder
Registered Member
Posts
14
Karma
0
OS
Hello Everyone,

I am encountering problems when I attempt to write a template function with MatrixBase and the template type as a parameter. For example, consider the following code:

Code: Select all
#include <Eigen/Core>
#include <vector>
#include <iostream>

using namespace std;
using namespace Eigen;

template <class Derived >
void vecfunc( vector<Derived>& realvec, const Derived& value )
{
        for( int i = 0; i < realvec.size(); ++i ) realvec[i] = value;
}

template<typename Derived>
void eigFuncA(Eigen::MatrixBase<Derived>& x)
{
        x.setOnes();
}

template<typename Derived>
void eigFuncB(Eigen::MatrixBase<Derived>& x, const Derived& value)
{
        x.setConstant(value);
}

int main( int argc, char** argv )
{
        vector<double> testvec(4,1.0);
        vecfunc(testvec,2.0);

        MatrixXd dynmat = MatrixXd::Ones(4,4);
        eigFuncA(dynmat);
        eigFuncB<double>(dynmat,2.0);
}


The function vecfunc (which accepts a templated STL vector and a template value) compiles and runs without issue. Similarly, eigFuncA (which accepts a templated MatrixBase) compiles and runs without issue. eigFuncB (which accepts a templated MatrixBase AND a template value), however, fails to compile.

When the final line of code is "eigFuncB(dynmat,2.0);" I receive the compile error:

vectortest.cpp: In function ‘int main(int, char**)’:
vectortest.cpp:33: error: no matching function for call to ‘eigFuncB(Eigen::MatrixXd&, double)’

When the final line of code is "eigFuncB<double>(dynmat,2.0);", I receive a large and unwieldy error message (sorry I can't post it, I exceed the post character limit). The message contains multiple lines with messages similar to "error: invalid use of incomplete type ‘struct Eigen::ei_traits<double>’"

Perhaps the problem is due to some rules about inheritance and template parameters I am unfamiliar with?

Any suggestions as to the source of the problem are greatly appreciated.

All the best!
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS
hi, MatrixBase is the base class of the Derived type, so here Derived is not at all a scalar type.
So you have to do:

template<typename Derived>
funcb(MatrixBase<Derived>& mat, const typename Derived::Scalar& val)
{
// ...
}
dubmarauder
Registered Member
Posts
14
Karma
0
OS
Great, thanks for clearing that up! I'm kicking myself for missing the design completly :).


Bookmarks



Who is online

Registered users: Bing [Bot], daret, Google [Bot], sandyvee, Sogou [Bot]