Skip to content

Instantly share code, notes, and snippets.

@tehrengruber
Created March 22, 2017 20:09
Show Gist options
  • Save tehrengruber/dbd537089085acaecd87de570179f382 to your computer and use it in GitHub Desktop.
Save tehrengruber/dbd537089085acaecd87de570179f382 to your computer and use it in GitHub Desktop.
Optional callback in C++
/**
* Functor behaving like an unset function pointer (nullptr) with
* arbitrary number of arguments.
*
* Usage:
* ```
* #include "Utils/void_cb.hpp"
*
* template <typename CB=void_cb>
* void f(CB callback=nullptr) {
* // ...
* if (callback != nullptr) {
* callback("whatever arguments your callback takes");
* }
* // ...
* }
* ```
*/
struct void_cb {
constexpr void_cb(void* = nullptr) {}
template <typename... T>
void operator()(T...) { assert(false); };
constexpr operator void*() const { return nullptr; }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment