Skip to content

Instantly share code, notes, and snippets.

@pkierski
Last active February 12, 2021 08:28
Show Gist options
  • Select an option

  • Save pkierski/db71e026b74a322c0b13865de0f91c08 to your computer and use it in GitHub Desktop.

Select an option

Save pkierski/db71e026b74a322c0b13865de0f91c08 to your computer and use it in GitHub Desktop.
DeferredCall
#include <memory>
#include <functional>
#include <exception>
class DeferredCall
{
public:
DeferredCall(std::function<void()> callable)
: callable{std::move(callable)}
{
}
~DeferredCall()
{
if(callable)
{
try
{
callable();
}
catch(const std::exception&)
{
}
}
}
void Cancel()
{
callable = decltype(callable){};
}
private:
std::function<void()> callable;
};
// example
#include <iostream>
void foo()
{
std::cout << "foo" << std::endl;
}
void bar(int x)
{
std::cout << "bar(" << x << ")" << std::endl;
}
int main(int argc, char* argv[])
{
DeferredCall deferredFoo(foo);
DeferredCall deferredBar1([]{bar(1);});
DeferredCall deferredBar42([]{bar(42);});
deferredBar1.Cancel();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment