c++ - 通过引用传递的特征参数

标签 c++ eigen eigen3 pybind11

我正在关注 Eigen 文档中的这个页面,试图了解 Eigen 参数的使用

https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html

下面的代码按预期工作

#include <iostream>
#include <Eigen/Dense>

// a - nonwriteable, b - writeable
void eigen_reference_class(
    const Eigen::Ref<const Eigen::Array<double, 
    Eigen::Dynamic, 3> >& a, Eigen::Ref<Eigen::Array<double, Eigen::Dynamic, 3> > b) {
    b = 2 * a;
}

void eigen_reference(const Eigen::Array<double, 1, 3>& a, Eigen::Array<double, 1, 3>& b) {
    b = 2*a;
}

template<typename Derived> 
void eigen_template(const Eigen::PlainObjectBase<Derived>& a, Eigen::PlainObjectBase<Derived>& b) {
    b = 2*a;
}

int main()
{
    Eigen::Array<double, 1, 3> a, b, c, d;
    a << 1, 2, 3;
    eigen_reference_class(a, b);
    eigen_reference(a, c);
    eigen_template(a,  d);
    std::cout << "a : \n" << a << std::endl;
    std::cout << "b: \n" << b << std::endl;
    std::cout << "c: \n" << c << std::endl;
    std::cout << "d: \n" << d << std::endl;

}

但是,如果数组的初始声明更改为

Eigen::Array<double, Eigen::Dynamic, 3> a, b, c, d;

然后程序将无法通过以下方式编译:

error: invalid initialization of non-const reference of type ‘Eigen::Array<double, 1, 3>&’ from an rvalue of type ‘Eigen::Array<double, 1, 3>’       
     eigen_reference(a, c);

即使只保留 a 的定义,也会因段错误而失败。

最佳答案

我喜欢看什么int在这种情况下这样做是因为它可以帮助我更轻松地理解在这种情况下发生的更复杂的事情。

假设您有一个 struct拿着int可以隐式转换为 int , 这样你就可以用它代替 int ,像这样:

struct Integer {
    int m_int;
    operator int() { return m_int; }
};

现在定义两个函数,一个接受 int const &和一个服用 int & .

void const_ref(int const &) {}
void ref(int &) {}

如果我们在这些函数中使用常规整数,则不会有任何意外。

int j = 3;
const_ref(j);
ref(j);

但是如果我们使用 Integer相反,它不再编译。

Integer i{2};
const_ref(i);
ref(i);

错误是这样的

error: no matching function for call to 'ref'
    ref(i);
    ^~~
note: candidate function not viable: no known conversion from 'Integer' to 'int &' for 1st argument
void ref(int &) {}
     ^
1 error generated.

现在的问题是,为什么const_ref工作但ref不是吗?

在调用 const_ref 时发生的情况是转换运算符为 int被调用,它返回一个临时的 int我们可以绑定(bind)一个常量引用。我们不能将可变引用绑定(bind)到这个临时对象,因为这会导致奇怪的效果。想象一下函数 ref修改参数,但在这种情况下,它会修改一个临时变量,并且不会向原始 Integer 写入任何内容你传入的……肯定是错误。


在你的代码中是一样的。 Eigen::Array<double, Eigen::Dynamic, 3>可以隐式转换为 Eigen::Array<double, 1, 3>但您不能将可变引用绑定(bind)到临时引用。

关于c++ - 通过引用传递的特征参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49269280/

相关文章:

c++ - Eigen::Map 默认模板参数如何工作?

c++ - 特征:模板函数中 MatrixBase 的默认类型?

c++ - 对于巨大的稀疏对称矩阵,哪个是 Spectra 库中最快的特征值求解器?

c++ - 指针算术递增后缀/前缀

c++ - 如何在制定目标后设置变量?

c++ - 存储指向 Eigen Vector 'segment' 的指针而不复制?

vector - 使用 Eigen 库查找 3D 向量的长度

c++ - 通过外部分配的数据调用 Eigen GEMM

c++ - 使用位运算的基数排序

c++ - 为什么 Bing Maps for Visual Studio 2013 C++ 打不开?