使用函数调用函子
我有一个算法,可以调用多个函数来处理其数据。这些函数中的每一个都共享并操作许多相同的变量。因此,我试图避免使用一组包含一长串引用参数的函数,因为我发现这会变得非常难以阅读,特别是因为其中许多变量都是 STL 容器。因此,我实现了一个函子来执行算法的工作,并为函子定义了一个函数包装器,如下所示,
class myfunctor {
private:
... list of shared members ...
void A(..args..) { ..do some work on shared members.. }
void B(..args..) { ..do some work on shared members.. }
void C(..args..) { ..do some work on shared members.. }
public:
void operator()(class1& X, class2& Y) {
A( .. );
..
B( .. );
..
C( .. );
..etc..
}
};
void algorithm(class1& X, class2& Y) {
myfunctor obj;
obj(X, Y);
}
我只是好奇是否有更好的方法来实现所有依赖于的几个函数相同的变量,这是否被认为是不好的做法?
I have an algorithm that calls several functions to process its data. Each of these functions share and manipulate many of the same variables. Therefore I'm trying to avoid having a set of functions that contain a long list of reference arguments as I find that to become very difficult to read, especially since many of these variables are STL containers. As a result, I have implemented a functor to perform the work of the algorithm and defined a function wrapper for the functor, as shown below
class myfunctor {
private:
... list of shared members ...
void A(..args..) { ..do some work on shared members.. }
void B(..args..) { ..do some work on shared members.. }
void C(..args..) { ..do some work on shared members.. }
public:
void operator()(class1& X, class2& Y) {
A( .. );
..
B( .. );
..
C( .. );
..etc..
}
};
void algorithm(class1& X, class2& Y) {
myfunctor obj;
obj(X, Y);
}
I'm just curious to see if there is perhaps a better way of implementing several functions that all depend on the same variables, and if this is considered bad practice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于有无数函数处理相同的共享数据,因此使它们成为以数据作为实例数据的类的成员函数是合理的选择。
然而,“函子”可能不是描述你的小动物的正确术语。
函子的行为很像一个简单的函数指针:它可以自由复制,并且通常从调用者的角度来看,似乎不会改变状态。虽然你的小动物显然不能自由复制,并且确实会改变状态。我想说你的野兽更像是一个状态机对象,通过函数调用从一个状态带到另一个状态。
干杯&呵呵,,
With umpteen functions working on the same shared data, making them member functions of a class with the data as instance data is the rational choice.
However, “functor” is perhaps not the correct term for your beastie.
A functor behaves much like a simple function pointer: it can be freely copied around, and usually, from the caller’s point of view, doesn’t appear to change state. While your beastie apparently cannot be freely copied around, and does appear to change state. I’d say your beastie is more like a state machine object, brought from state to state by the function calls.
Cheers & hth.,