Skip to content

Instantly share code, notes, and snippets.

@dtrugman
Last active April 22, 2024 00:34
Show Gist options
  • Save dtrugman/d3b10ad0a91b2f069f07f9311d24932a to your computer and use it in GitHub Desktop.
Save dtrugman/d3b10ad0a91b2f069f07f9311d24932a to your computer and use it in GitHub Desktop.
GO's defer-like implementation for CPP
/*
* Copyright (c) 2020-present Daniel Trugman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <functional>
#define var_defer__(x) defer__ ## x
#define var_defer_(x) var_defer__(x)
#define ref_defer(ops) defer var_defer_(__COUNTER__)([&]{ ops; }) // Capture all by ref
#define val_defer(ops) defer var_defer_(__COUNTER__)([=]{ ops; }) // Capture all by val
#define none_defer(ops) defer var_defer_(__COUNTER__)([ ]{ ops; }) // Capture nothing
class defer
{
public:
using action = std::function<void(void)>;
public:
defer(const action& act)
: _action(act) {}
defer(action&& act)
: _action(std::move(act)) {}
defer(const defer& act) = delete;
defer& operator=(const defer& act) = delete;
defer(defer&& act) = delete;
defer& operator=(defer&& act) = delete;
~defer()
{
_action();
}
private:
action _action;
};
#include <iostream>
#include "defer.hpp"
int main()
{
std::string message("goodbye");
// Usage without macro wraps
defer defer_it([&message]{ std::cout << message << std::endl; });
// Use macro that captures nothing
none_defer(std::cout << "msg hard-coded" << std::endl);
// Use macro that captures all members by value
val_defer(std::cout << "msg by val: " << message << std::endl);
// Use macro that captures all members by reference
ref_defer(std::cout << "msg by ref: " << message << std::endl);
message += " friend";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment