使用特征标头的模板函数
Template function using Eigen header
我想写一个函数来计算用特征定义的向量的范数。最小工作示例:
#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;
}
相关文章:
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 特征:模板函数中矩阵的平面图
- 特征模板化函数和维度
- 具有相同特征的两个对象是否只在内存中存储一次?无论定义它们的函数是什么,都是不同的
- 用于检测函数类型是否为否的特征
- 根据类型特征更改函数定义?
- 以特征类型作为参数的泛型函数回调
- 基于 SFINAE 的特征实现问题与函数模板重载
- 如何在没有返回值的情况下使用(特征)unaryExpr 和 lambda 函数?
- 如何使用类型特征将函数的通用引用参数限制为 r 值引用?
- 如何构造一个类型特征,可以判断一个类型的私有方法是否可以在另一个类型的构造函数中调用?
- 特征::向量;在函数中使用 Eigen::Matrix3f 的值初始化向量,大于 4 个条目
- 带有特征的函数指针
- 特征:创建一个具有函数的三维阵列
- 如何根据传递给函数的变量定义特征矩阵大小
- Lambda 函数在特征中按元素方向
- 特征运算符如何在内部解释为 MKL 函数?
- 默认参数的函数特征
- 了解函数特征模板的工作原理.特别是,指向成员函数的指针是怎么处理的
- 成员函数特征