Suppose I have the following code that I wish to refactor:
int toFuture() { precalc(); int calc = 5 * foobar_x() + 3; postcalc(); return calc; } int toPast() { precalc(); int calc = 5 * foobar_y() - 9; postcalc(); return calc; }
In classic-C, I would refactor this code into a worker() which accepts a function pointer that does the calculation: common code in worker(), specific code provided by function pointer.
With C++11, should I be using a lambda instead? If so, how would I implement it, in this case?
Edit: it just crossed my mind that a template may also work. How would a template implementation compare against the other two?
The third argument, callback , is a function that you can call in non-async handlers to send a response. The callback function takes two arguments: an Error and a response. When you call it, Lambda waits for the event loop to be empty and then returns the response or error to the invoker.
Callbacks make sure that a function is not going to run before a task is completed but will run right after the task has completed. It helps us develop asynchronous JavaScript code and keeps us safe from problems and errors.
The main difference between a normal function and a callback function can be summarized as follows: A normal function is called directly, while a callback function is initially only defined. The function is only called and executed once a specific event has occurred.
The functions that receive the callback function as a parameter are the ones responsible to call back the callback function. Callbacks are great because they open up a lot of programming possibilities.
One approach:
template<typename CalcFuncT> int perform_calc(CalcFuncT&& calcfunc) { precalc(); int const calc = std::forward<CalcFuncT>(calcfunc)(); postcalc(); return calc; } int main() { perform_calc([]{ return 5 * foobar_x() + 3; }); // toFuture perform_calc([]{ return 5 * foobar_y() - 9; }); // toPast }
If you are wanting a template approach using C++11 features, that could look as simple as:
template<typename FuncType> auto calculation(FuncType&& func) -> decltype(func()) { precalc(); auto ret = func(); postcalc(); return ret; }
You would then simply call your calculation
function and pass it either a lambda, a functor, or a function-pointer. Your only souce of difficulty in this instance would be if you passed a function that had a void
return-type ... in that case you will get a compiler error (which is a good thing vs. a runtime error).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With