I want to call a function foo and let it behave differently.
(I’m adopting Strategy or Command pattern. They look similar to me.)
My overall plan is as follows..
First, define foo to take boost::function type
foo(boost::function<someType> execFunction) { // do something execFunction(args); // do something }
Then, I give foo() different functions(as argument) depending on what I want.
Would this work? or Would you advise against it?
Any comments are welcome.
edit
Minor related question is,
sometimes execFunction needs 1 argument, and other times it needs 2 arguments.
I could use boost::function for both cases and just ignore the 2nd argument when not needed.
Is there a cleaner way to do this?
This works very well. But sometimes it is preferable to work with a
functor so your callers are free to choose what is best for them and to prevent the smalll overhead that comes with a
boost::function:You can also add an overload for the specific
boost::functionto take the object by reference.And possibly have that overloaded for constness as well.
For the case of accepting
boost::functionobjects of different arity, I’d use overloading. If you go that route, avoid the templated version as you are going to run into trouble as soon as your users try to work with functors (as opposed toboost::functionwith different arity). This trouble is resolvable, but can get messy. You would need to dispatch the call to something that detects the arity of the funtor and executes the proper call. But as you said that templates are your weak-point, this isn’t really recommended.