将一个函子的实例传递给另一个函子
Passing an instance of a functor to another functor
出于结构原因,我希望能够将函子的实例传递给另一个函子。目前,我通过将指向函数的指针传递给我的函子来实现等效的东西。
我试图在下面的一些最小代码中封装这个想法:
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)
{ }
// ...
};
相关文章:
- 如何将模板的实例传递给另一个模板的另一个实例?
- 如何在另一个类中创建类的实例?
- 如果模板参数是另一个模板的实例化,则键入特征测试
- 重载运算符*以获取对另一个类的实例的引用
- 我有一个类,它创建了另一个类的实例.如何将变量通过第一个类传递到第二个类的实例化中?
- 如何正确实例化静态字段 tat 是另一个类对象
- C++ - 使用另一个类的构造函数实例化一个对象
- 如何使用另一个模板化类的实例模板化类?
- 在另一个类中创建类实例时出现问题
- C++:递归地将字符串中一个字母的所有实例替换为另一个字母
- 另一个类中嵌套模板的外部实例化
- 如何为包含另一个类实例的数组制作常量 getter?
- 如何将模板化类实例作为模板参数传递给另一个模板?
- 如何在 C 中包装C++具有参数的类方法或返回另一个C++类的实例?
- 如何将对象函数的实例传递给另一个函数
- "new operator"将另一个类实例化为工厂?
- 如何在C++中将类的实例完全重新分配给同一类的另一个实例(然后删除原始对象)?
- 如何使用 c++ 从另一个 cpp 文件中的 main.cpp 调用实例化类
- 无法从派生类型的作用域访问另一个实例的受保护成员
- 类实例的C++/向量作为另一个类的属性