使用特征标头的模板函数

Template function using Eigen header

本文关键字:函数 特征      更新时间:2023-10-16

我想写一个函数来计算用特征定义的向量的范数。最小工作示例:

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

有没有人有提示该怎么做。因为我不知道还能尝试什么,也没有真正理解编译过程中的错误消息

虽然可以将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;
}