In C++ when I have algorithm which could accept different behaviour in runtime I rather use function pointer.
For example, a program for drawing charts has one algorithm to draw line which can accept any function to specialize shape of this line.
In Java there are no function pointers and I am obliged to use either the strategy pattern or reflection (or another pattern).
How to to enable special behavior to be selected at runtime in my programme? Strategy pattern either function pointer?
There are multiple ways to implement the strategy pattern in C++.
All three can get the job done so which one to choose highly depends on your problem.
You mentioned that you want to use a strategy to draw a diagram. This is a complex use-case in my opinion and you shall go with option one, because your strategy object may query settings like preferred colors and so on and you may want to store the strategies somewhere, such that the user can select them in a combo-box.
A function object is really nice if you want to give the clients (your co-workers) a lot of flexibility. In my current project we use function objects for stop-criterion testing in an algorithm. This is very nice with lambdas in C++11 as long as the functionality does not become too complex.
The policy base way may be the fastest but it needs to know the type at compile-time. No DLLs base plugins when using this. At least not until you encapsulate your implementation in a class hierarchy:
I think good advices are:
In Java function pointers are implemented using functors. Create an interface with one function and pass instances of it instead of function pointers. Let's your code in C++ looked like:
In Java this would look like:
Take a look at Guava's Function class. This is also not a bad approach for C++ as well. It is more readable and allows user to pass in objects with state as opposed to static functions.
It depends entirely on what you are doing with your functor. If you want to use it as a one-off to do an operation, you want to use a template. As an example, see any of the standard algorithms - say,
std::sort
:If you want to store your functors for use later, you want
std::function
- a type-erased functor:Which you would use like:
You definitely don't want to use explicit function pointers - that will severely limit the usability of your class/function. You want to allow people to pass in objects too. This is, after all, C++ and not C!