That is really nice. Could you expand on how this works a little "You can also avoid problems with exceptions and std::function’s dynamic allocation by using a template instead:"
std::function can store function pointers (and member function pointers) by value, but using a function-like object that defines operator()—or by extension std::bind()—requires dynamic allocation, which can throw. The templated version, on the other hand, always stores its parameter by value. Come to think of it, you could also make the constructor take an rvalue reference (F&&) to use move construction instead of copy construction.
... because the compiler knows how big the function like object will be at compile time when the template is used but it only knows it at runtime if the class is used. ...
Comments
That is really nice. Could you expand on how this works a little "You can also avoid problems with exceptions and std::function’s dynamic allocation by using a template instead:"
std::function can store function pointers (and member function pointers) by value, but using a function-like object that defines operator()—or by extension std::bind()—requires dynamic allocation, which can throw. The templated version, on the other hand, always stores its parameter by value. Come to think of it, you could also make the constructor take an rvalue reference (F&&) to use move construction instead of copy construction.
... because the compiler knows how big the function like object will be at compile time when the template is used but it only knows it at runtime if the class is used. ...
I am guessing this is the situation?