特征c ++铸造

时间:2015-05-20 02:22:09

标签: c++ matrix casting eigen

我在使用Eigen库乘以两个矩阵时遇到了麻烦。我有以下功能。这是我想做的一个小例子:

程序名称:testMatOp.cpp

#include <iostream>
#include <Eigen/Dense>
using namespace std;

template <typename DerivedA, typename DerivedB>
void multiply(const Eigen::MatrixBase<DerivedA> &A,
               const Eigen::ArrayBase<DerivedB> &B){
  Eigen::MatrixXf C(2,4);
  C.array() = A.array().rowwise() * B.cast<float>();
}

int main()
{
  Eigen::MatrixXf A(2,4);
  Eigen::MatrixXf C(2,4);
  //igen::VectorXf v(4);
  Eigen::Array<int,1,Eigen::Dynamic>B;
  B.resize(4);

  A << 1, 2, 6, 9,
         3, 1, 7, 2;

  B << 0,
       1,
       0,
       0;

  multiply(A,B);
}

我想传递矩阵A和矢量B乘以。据我所知,Eigen不进行自动升级,B需要作为浮点向量进行转换,以便进行乘法运算。当我编译时,我得到以下编译错误

testMatOp.cpp:34:44: error: expected primary-expression before 'float'
testMatOp.cpp:34:44: error: expected ';' before 'float'
testMatOp.cpp: In instantiation of 'void multiply(const Eigen::MatrixBase<Derived>&, const Eigen::ArrayBase<DerivedB>&) [with DerivedA = Eigen::Matrix<float, -1, -1>; DerivedB = Eigen::Array<int, 1, -1>]':
testMatOp.cpp:54:15:   required from here
testMatOp.cpp:34:3: error: no match for 'operator*' in '((const Eigen::DenseBase<Eigen::ArrayWrapper<const Eigen::Matrix<float, -1, -1> > >*)(&(& A)->Eigen::MatrixBase<Derived>::array<Eigen::Matrix<float, -1, -1> >()))->Eigen::DenseBase<Derived>::rowwise<Eigen::ArrayWrapper<const Eigen::Matrix<float, -1, -1> > >() * B.Eigen::ArrayBase<Derived>::cast<NewType>'
testMatOp.cpp:34:3: note: candidates are:
In file included from ../3rdparty/Eigen/Core:336:0,
                 from ../3rdparty/Eigen/Dense:1,
                 from testMatOp.cpp:26:

我可能做错了什么。我确实看过这篇文章: Here is the picture representing the problem 这正确地描述了如何投射,但我无法使它适用于这个例子。

任何帮助将不胜感激。谢谢!

-a

2 个答案:

答案 0 :(得分:7)

由于cast()是模板成员函数,因此在模板代码中,您必须在其前面添加template关键字:

B.template cast<float>();

答案 1 :(得分:3)

Bdependent name。要访问其模板成员cast,您必须编写

B.template cast

C ++是上下文相关的。遇到<时,它会尝试确定它是operator<还是尖括号。

// std::vector is a template, so < is an angle bracket
std::vector < float >

// 3 is not a template, so < is operator<
3 < 5

但是,B的类型为const Eigen::ArrayBase<DerivedB>&,具体取决于模板参数DerivedB。 C ++无法确定B.cast是否为模板。发生这种情况时,C ++总是猜测它不是模板,并将以下<解释为operator<

为什么C ++是如此愚蠢,它无法识别以前声明的模板ArrayBase::cast?好吧,有人可能会专攻ArrayBase<int>

template<>
class ArrayBase<int>
{
  public:
    int cast = 3;
};

因此无法推断B.cast是模板。