开发者

Using a function to call a functor

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?


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.,

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜