我想编写一个函数来计算用 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>’
有没有人知道该怎么做。因为我既不知道还能尝试什么,也没有真正理解编译期间的错误信息
最佳答案
虽然 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;
}
关于c++ - 使用 Eigen header 的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50232783/