Welcome, guest! Login / Register - Why register?
Psst.. new poll here.
Psst.. new forums here.
Microsoft is blocking us again (TY IP Reputation!) so just use oauth login instead. :)

Paste

Pasted as C++ by mutanabbi ( 11 years ago )
#include <iostream>
#include <type_traits>

int foo() {
    std::cout << "foo" << std::endl;
    return 1;
}

int bar(int a, std::string b)
{
    std::cout << a << " " << b << std::endl;
    return 2;
}

template <typename F>
class on_scope_exit_call
{
    F m_on_exit;

public:
    on_scope_exit_call(F&& f) : m_on_exit(std::forward<F>(f))
    {}

    /// Make a deferred call on destroy
    ~on_scope_exit_call()
    {
        m_on_exit();
    }
};

template <typename F>
auto make_on_scope_exit(F&& f)
{
    return on_scope_exit_call<F>{std::forward<F>(f)};
}

template <typename F, typename ... Args>
auto make_on_scope_exit(F&& f, Args&& ... args)
{
    return make_on_scope_exit([f, &args;...]() { f(std::forward<Args>(args)...); });
}

int main(int argc, char* argv[])
{
    std::cout << "START" << std::endl;
    {
        std::function<int ()> f = foo;
        auto sg = make_on_scope_exit([=]() { std::cout << "exit" << std::endl;});
        auto sg1 = make_on_scope_exit(foo);
        auto sg2 = make_on_scope_exit(bar, 1, std::string("ilya"));
        //auto sg3 = make_on_scope_exit(static_cast<void (*)()>(nullptr));
        //auto sg4 = make_on_scope_exit(std::function<void ()>());
        auto sg5 = make_on_scope_exit(f);
        std::cout << "Still in the scope" << std::endl;
    }
    std::cout << "FINISH" << std::endl;
    return 0;
}

 

Revise this Paste

Parent: 78612
Your Name: Code Language: