Derived to MatrixBase<Derived> 转换背后的故事
Story behind Derived to MatrixBase<Derived> conversion
将矩阵对象作为 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 的差异从何而来?
以及为什么需要转换?
提前致谢!
sizeof
适用于编译时类型。参见 sizeof
When applied to an expression, sizeof does not evaluate the
expression, and even if the expression designates a polymorphic
object, the result is the size of the static type of the expression.
这意味着无论实例是什么类型,您都可以获得 MatrixBase<Derived>
的大小。
表达式 sizeof(b)
与您写 sizeof(MatrixBase<Derived>)
完全相同。
sizeof
是在编译时求值的,所以它与声明的(静态)对象类型有关。 b
是 MatrixBase<Derived>
类型(忽略引用,就像 sizeof
一样),它很可能是一个空基数 class,因此大小为 1.
另一方面,m
是 Matrix<float, 2, 2>
类型,显然在您的平台上大小为 16。
我创建了一个 live example 来演示 sizeof
的这种行为。
将矩阵对象作为 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 的差异从何而来?
以及为什么需要转换?
提前致谢!
sizeof
适用于编译时类型。参见 sizeof
When applied to an expression, sizeof does not evaluate the expression, and even if the expression designates a polymorphic object, the result is the size of the static type of the expression.
这意味着无论实例是什么类型,您都可以获得 MatrixBase<Derived>
的大小。
表达式 sizeof(b)
与您写 sizeof(MatrixBase<Derived>)
完全相同。
sizeof
是在编译时求值的,所以它与声明的(静态)对象类型有关。 b
是 MatrixBase<Derived>
类型(忽略引用,就像 sizeof
一样),它很可能是一个空基数 class,因此大小为 1.
m
是 Matrix<float, 2, 2>
类型,显然在您的平台上大小为 16。
我创建了一个 live example 来演示 sizeof
的这种行为。