zodiac
zodiac

Reputation: 301

Template function using Eigen header

I want to write a function that computes the norm of an Vector defined with Eigen. Minimum working example:

#include <iostream>
#include <Eigen/Dense>

using namespace Eigen;


template<typename t>
t norm( Matrix<t,Dynamic,1> RR ){
    t result = ( t ) 0;
    for ( auto i = 0 ; i < RR.rows(); i++ )
            result += RR( i ) * RR( i );
    }

    return result;
}


int main(){
    Matrix<float , 3 , 1 > test;
    test << 1,2,3;

    std::cout << test << std::endl;
    std::cout << norm( test ) << std::endl;
}

If I compile this code I get the following Error:

chem:~/programs/cpp/charge_ana> g++ -std=c++11 test.cpp -o test
test.cpp: In function ‘int main()’:
test.cpp:28:26: error: no matching function for call to    
‘norm(Eigen::Matrix<float, 3, 1>&)’
std::cout << norm( test ) << std::endl;
test.cpp:28:26: note: candidate is:
test.cpp:9:3: note: template<class t> t norm(Eigen::Matrix<Scalar, -1, 1>)
t norm( Matrix<t,Dynamic,1> RR ){
^
test.cpp:9:3: note:   template argument deduction/substitution failed:
test.cpp:28:26: note:   template argument ‘3’ does not match ‘#‘integer_cst’ not supported by dump_decl#<declaration error>’
std::cout << norm( test ) << std::endl;
                      ^
test.cpp:28:26: note:   ‘Eigen::Matrix<float, 3, 1>’ is not derived from ‘Eigen::Matrix<Scalar, -1, 1>’

Does anybody has a hint what to do. Because I neither know what else to try nor do I really understand the error message during compilation

Upvotes: 3

Views: 671

Answers (1)

chtz
chtz

Reputation: 18807

While an Eigen::Matrix<float, 3, 1> can be converted to an Eigen::Matrix<float, Eigen::Dynamic, 1> this will not be done automatically before doing template deduction. You can either call:

norm<float>(test)

or you can add another template parameter for the size:

template<typename t, int size>
t norm( const Matrix<t,size,1>& RR ){
    t result = RR.squaredNorm(); // this does the same as your loop

    return result;
}

Upvotes: 7

Related Questions