代码之家  ›  专栏  ›  技术社区  ›  OnurA

衍生到MatrixBase转换背后的故事

  •  4
  • OnurA  · 技术社区  · 7 年前

    将矩阵对象作为MatrixBase引用传递给函数时会发生什么?我不明白幕后到底发生了什么。

    功能代码示例如下:

    #include <Eigen/Core>
    #include <iostream>
    
    using namspace Eigen;
    
    template <typename Derived>
    void print_size(const MatrixBase<Derived>& b)
    {
      std::cout << "size (rows, cols): " << b.size() << " (" << b.rows()
                << ", " << b.cols() << ")" << std::endl;
      std::cout << sizeof(b) << std::endl;
    }
    
    int main() {
        Matrix<float, 2, 2> m;
        m << 0.0, 0.1,
             0.2, 0.3;
    
        print_size(m);
        std::cout << sizeof(m) << std::endl;
    }
    

    它提供以下输出:

    size (rows, cols): 4 (2, 2)
    1
    16
    

    16对1的区别来自哪里?

    还有,为什么需要进行转换?

    提前感谢!

    2 回复  |  直到 7 年前
        1
  •  7
  •   Angew is no longer proud of SO    7 年前

    sizeof 在编译时求值,因此它与声明的(静态)对象类型有关。 b 属于类型 MatrixBase<Derived> (忽略引用,就像 sizeof公司 ,这很可能是一个空基类,因此大小为1。

    m 另一方面,是类型 Matrix<float, 2, 2> ,显然您的平台上有16号。

    我创建了一个 live example 展示以下行为: sizeof公司 .

        2
  •  3
  •   Jaa-c    7 年前

    sizeof 适用于编译时类型。看见 sizeof

    当应用于表达式时,sizeof不会计算 表达式,即使表达式指定多态 对象,结果是表达式的静态类型的大小。

    这意味着您可以获得 MatrixBase<Derived> 无论实例是什么类型。

    表达式 sizeof(b) 就像你写的一样 sizeof(MatrixBase<Derived>) .