将一个函子的实例传递给另一个函子

Passing an instance of a functor to another functor

本文关键字:实例 另一个 一个      更新时间:2023-10-16

出于结构原因,我希望能够将函子的实例传递给另一个函子。目前,我通过将指向函数的指针传递给我的函子来实现等效的东西。

我试图在下面的一些最小代码中封装这个想法:

class A
{
private:
    double _x, _y, _z;
public:
    A (double x, double y, double z) : _x(x), _y(y), _z(z) {};
    void operator() (double t) const
    {
        // Some stuff in here that uses _x, _y, _z, and t.
    }
};
class B
{
private:
    // What is the type of the functor instance?
    ??? A ???
public:
    // How do I pass the instance of A into B at initialisation?
    B (??? A ???) :  ??? : {};
    void operator() (double tau) const
    {
        // Something that uses an instance of A and tau.
    }
};
int main(void)
{
    // I want to do something like this:
    A Ainst(1.1, 2.2, 3.3); // Instance of A.
    B Binst(Ainst);         // Instance of B using instance of A.
    Binst(1.0);             // Use the instance of B.
    return 0
}

从本质上讲,我希望能够链接函子。如上所述,我目前通过将函数指针与变量 x、y 和 z 一起传递给 B 来做到这一点。在我的代码中,B 是模板化的,目标是编写一次,然后重用它,以后无需任何修改,这意味着将 x、y 和 z 交给 B 并不理想。另一方面,A将为我编写的每个程序进行定制。我不介意B很乱,但我希望A漂亮干净,因为这是将要暴露的部分。

对于那些了解一些量子力学的人来说,B是薛定谔方程(或主方程),A是时间依赖的哈密顿量。变量 x、y 和 z 用于构造哈密顿算符,t 是时间,允许我使用 odeint 库(所以我使用 ublas 和其他几个 Boost 位)。

使用引用?

class A { /* ... */ };
class B
{
    A &a;
public:
    B(const A &my_a)
        : a(my_a)
    { }
    // ...
};