mirror of
https://github.com/SerenityOS/serenity.git
synced 2025-01-22 09:21:57 -05:00
e4c36876d2
Just enough to make it possible to pass a lambda to a constexpr function taking an AK::Function parameter and have that constexpr function call the passed-in AK::Function. The main thing is that bit_cast<>s of pointers aren't ok in constexpr functions, and neither is placement new. So add a union with stronger typing for the constexpr case. The body of the `if (is_constexpr_evaluated())` in `init_with_callable()` is identical to the `if constexpr` right after it. But `if constexpr (is_constexpr_evaluated())` always evaluates `is_constexpr_evaluated()` in a constexpr context, so this can't just add ` || is_constexpr_evaluated()` to that `if constexpr`.
56 lines
845 B
C++
56 lines
845 B
C++
/*
|
|
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
|
|
*
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
|
*/
|
|
|
|
#pragma once
|
|
|
|
#include <AK/StdLibExtras.h>
|
|
|
|
namespace AK {
|
|
|
|
template<typename Callback>
|
|
class ScopeGuard {
|
|
public:
|
|
constexpr ScopeGuard(Callback callback)
|
|
: m_callback(move(callback))
|
|
{
|
|
}
|
|
|
|
constexpr ~ScopeGuard()
|
|
{
|
|
m_callback();
|
|
}
|
|
|
|
private:
|
|
Callback m_callback;
|
|
};
|
|
|
|
template<typename Callback>
|
|
class ArmedScopeGuard {
|
|
public:
|
|
ArmedScopeGuard(Callback callback)
|
|
: m_callback(move(callback))
|
|
{
|
|
}
|
|
|
|
~ArmedScopeGuard()
|
|
{
|
|
if (m_armed)
|
|
m_callback();
|
|
}
|
|
|
|
void disarm() { m_armed = false; }
|
|
|
|
private:
|
|
Callback m_callback;
|
|
bool m_armed { true };
|
|
};
|
|
|
|
}
|
|
|
|
#if USING_AK_GLOBALLY
|
|
using AK::ArmedScopeGuard;
|
|
using AK::ScopeGuard;
|
|
#endif
|