使用Eigen标题的模板函数

时间:2018-05-08 11:44:18

标签: c++ c++11 templates eigen

我想编写一个函数来计算用Eigen定义的Vector的范数。最低工作示例:

#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;
}

如果我编译此代码,我会收到以下错误:

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>’

是否有人暗示该怎么做。因为我既不知道还有什么可以尝试,也不是我真正理解编译期间的错误信息

1 个答案:

答案 0 :(得分:5)

虽然可以将Eigen::Matrix<float, 3, 1>转换为Eigen::Matrix<float, Eigen::Dynamic, 1>,但在执行模板扣除之前不会自动完成此操作。你可以打电话:

norm<float>(test)

或者您可以为尺寸添加另一个模板参数:

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;
}