Skip to content

Instantly share code, notes, and snippets.

@byBretema
Last active October 25, 2023 20:43
Show Gist options
  • Save byBretema/af7689992649f6277c843f0798539513 to your computer and use it in GitHub Desktop.
Save byBretema/af7689992649f6277c843f0798539513 to your computer and use it in GitHub Desktop.
C++ : Cloning Go Defer keyword functionality
// Check playground in: https://www.mycompiler.io/view/7pXriajivQt
#include <iostream>
#include <memory>
#include <functional>
//--- CONCAT ----------------------------------------------
#define detail_CONCAT(a, b) a##b
#define CONCAT(a, b) detail_CONCAT(a, b)
//---------------------------------------------------------
//--- DEFER -----------------------------------------------
#define detail_DEFER0 std::unique_ptr<void, std::function<void (void *)>>
#define detail_DEFER1 []() { static int a=0; return &a; }
#define DEFER(fn) auto CONCAT(defer_,__LINE__) = detail_DEFER0( detail_DEFER1(), [&](void *) { fn; } )
//---------------------------------------------------------
int main()
{ // In: Scope 0
{ // In: Scope 1
std::vector<std::string> names = { "Lisa", "John" };
DEFER( std::cout << "Bye bye, have a good day " << names[0] << " and you too "<< names[1] << "!\n" );
std::cout << "Hello mate!\n";
std::cout << "Hey, nice to see you all!\n";
std::cout << "...\n" << "...\n" << "...\n";
} // Out: Scope 1
std::cout << "Same to you!" << std::endl;
return 0;
} // Out: Scope 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment