簡體   English   中英

DenseBase,自動和二進制操作表示數組具有不同的形狀

[英]DenseBase, auto, and binary operation says arrays have different shape

我編寫了一個將兩個DenseBase作為參數的函數。

該函數使用.derived().array()ArrayMatrix都轉換為Array

我厭倦了多次編寫derived並使用自動。

但是auto會導致奇怪的錯誤。 Eigen抱怨x2y2形狀不同。

如果我不想.derived().array()編寫.derived().array() ,該怎么用?

Eigen來自https://github.com/eigenteam/eigen-git-mirror.git

#include <Eigen/Eigen>
int main() {
    Eigen::ArrayXf x(3);
    Eigen::ArrayXf y(3);
    x << 1, 2, 3;
    y << 4, 5, 6;
    // x.derived().array() * y.derived().array();
    auto x2 = x.derived().array();
    auto y2 = y.derived().array();
    y2 = x2 * y2; 
}

運行時錯誤:

CwiseBinaryOp.h:110: ...

Assertion `aLhs.rows() == aRhs.rows() 
           && aLhs.cols() == aRhs.cols()' failed.

您可以通過auto x2 = x.array().derived();來解決運行時問題auto x2 = x.array().derived(); ,即:反向數組並派生。 但是,此處不建議使用auto 這就是為什么。 說您有:

template <typename T> void foo(DenseBase<T> &x);

如果TArray<>x.array().derived()Array<>並且x2將是x的深層副本。 在這種情況下,您想使用auto& x2 = ...

如果T是其他東西,例如Matrix<> ,則auto x2 = x.array().derived(); 非常好,但不是auto& x2 = ...

因此,您真正想要的是一些復雜的東西:

internal::ref_selector<std::decay<decltype(x.array().derived())>::type>::non_const_type
  x2 = x.array().derived();

不是很好 :(

一個更簡單的解決方案是,即使對於數組世界中已經存在的輸入,也不必打擾並創建ArrayWrapper

ArrayWrapper<T> x2(x.derived());

另一個簡單的解決方案是強制調用方在數組世界中傳遞表達式:

template <typename T> void foo(ArrayBase<T> &x) {
  T& x2(x.derived());
  ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM