使用CwiseUnaryOp作为左值

问题描述 投票:1回答:1

我正在使用Eigen的EIGEN_MATRIXBASE_PLUGIN功能来实现CwiseUnary表达式,而我在使用operator =扩展此工作时遇到了麻烦

我正在使用一个有两个成员的结构:.val_和.d_,并且我添加了一个CwiseUnaryOp来访问它们:

template<typename T>
struct d_Op {
  EIGEN_EMPTY_STRUCT_CTOR(d_Op)
  typedef T result_type;
  EIGEN_DEVICE_FUNC
  EIGEN_STRONG_INLINE const result_type& 
    operator()(const stan::math::fvar<T> &v) const { return v.d_; }
};

template<typename T>
struct val_Op {
  EIGEN_EMPTY_STRUCT_CTOR(val_Op)
  typedef T result_type;
  EIGEN_DEVICE_FUNC
  EIGEN_STRONG_INLINE const result_type& 
    operator()(const stan::math::fvar<T> &v) const { return v.val_; }
};

inline const CwiseUnaryOp<d_Op<typename stan::partials_type<Scalar>::type>, const Derived>
d_() const { return CwiseUnaryOp<d_Op<typename stan::partials_type<Scalar>::type>,
                                 const Derived>
    (derived(), d_Op<typename stan::partials_type<Scalar>::type>());
}

inline const CwiseUnaryOp<val_Op<typename stan::partials_type<Scalar>::type>, const Derived>
val_() const { return CwiseUnaryOp<val_Op<typename stan::partials_type<Scalar>::type>,
                                 const Derived>
    (derived(), val_Op<typename stan::partials_type<Scalar>::type>());
}

这样,给定Matrix<stan::math::fvar<double>,-1,-1> m类型的矩阵,我可以简单地写:m.val_()

这一切都很好,但我想扩展它来写这些值,而不是只读它们(即m.val_() = MatrixXD::Random(int,int))。但我无法弄清楚如何重载=运算符,给我这样的错误:

test.cpp:30:14: error: no match for ‘operator=’ (operand types are ‘const 
Eigen::CwiseUnaryOp<Eigen::MatrixBase<Eigen::Matrix<stan::math::fvar<double>, 
-1, -1> >::val_Op<double>, const Eigen::Matrix<stan::math::fvar<double>, -1, -1> >’ 
and ‘Eigen::MatrixXd’ {aka ‘Eigen::Matrix<double, -1, -1>’})

我错过了一些非常明显的东西吗?

编辑:使用CwiseUnaryView时的输出:

test.cpp:30:14: error: no match for ‘operator=’ 
(operand types are ‘const Eigen::CwiseUnaryView<Eigen::MatrixBase<Eigen::Matrix<stan::math::fvar<double>, -1, -1> >::val_Op<double>, const Eigen::Matrix<stan::math::fvar<double>, -1, -1> >’ 
and ‘Eigen::MatrixXd’ {aka ‘Eigen::Matrix<double, -1, -1>’})
   a.val_() = inp;
c++ eigen eigen3
1个回答
1
投票

这是一个带有虚拟fvar实现的最小工作示例,并在任何类之外定义CwiseUnaryView

#include <Eigen/Core>

template<class X>
struct fvar
{
    X d_, val_;
};

template<typename T>
struct d_Op {
  EIGEN_EMPTY_STRUCT_CTOR(d_Op)
  typedef T result_type;
  EIGEN_DEVICE_FUNC
  EIGEN_STRONG_INLINE const result_type& 
    operator()(const fvar<T> &v) const { return v.d_; }
  EIGEN_DEVICE_FUNC
  EIGEN_STRONG_INLINE result_type& 
    operator()(fvar<T> &v) const { return v.d_; }
};

void foo(Eigen::Matrix<fvar<float>, 4,4> &out, Eigen::Matrix4f const &in)
{
    Eigen::CwiseUnaryView<d_Op<float>, Eigen::Matrix<fvar<float>, 4,4> > view(out);
    view = in;
}

启用优化后,这将编译为一个简单的循环:https://godbolt.org/z/mgktfv

© www.soinside.com 2019 - 2024. All rights reserved.