c++ - 使用 Eigen header 的模板函数

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

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

最佳答案

虽然 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/

相关文章:

java - 通过网络从 C++ 客户端向 Java 服务器发送字符串

c++ - Clang 中的嵌套 C 数组结构对齐

templates - 如果... !true nunjucks 中的条件渲染

c++ - GoogleTest 测试夹具说明

c++ - 为什么法 vector 的顶点属性不起作用?

c++ - c++ 中的累积函数故障无法找到均值

C++ 我应该使用模板,我即将创建一个词法分析器,为什么它应该是有限的字符?

c++ - 在不需要时使用 "template"和 "typename"消歧器

c++ - 静态单例?

c++ - 参数必须是另一个模板类的模板类