Wrong results using auto with Eigen

前端 未结 1 1702
夕颜
夕颜 2020-12-07 01:52

I got different results using auto and using Vector when summing two vectors.

My code:

#include \"stdafx.h\"
#include 
#         


        
相关标签:
1条回答
  • 2020-12-07 02:42

    The auto keyword tells the compiler to "guess" the best object based on the right hand side of the =. You can check the results by adding

    std::cout << typeid(resAuto).name() <<std::endl;
    std::cout << typeid(resVector3).name() <<std::endl;
    

    to foo (don't forget to include <typeinfo>).

    In this case, after constructing the temporary Vector3, the operator+ method is called, which creates a CwiseBinaryOp object. This object is part of Eigens lazy evaluation (can increase performance). If you want to force eager evaluation (and therefore type determination), you could use

    const auto resAuto = (Ha + Vector3(0.,0.,j * 2.567)).eval();
    

    instead of your line in foo.

    A few side notes:

    • Vector3 is identical to the Vector3d class defined in Eigen
    • You can use #include <Eigen/Core> instead of #include <Eigen/Geometry> to include most of the Eigen headers, plus certain things get defined there that should be.
    0 讨论(0)
提交回复
热议问题