Console Library 8.0.0
A header-only library that makes C++ simple
Loading...
Searching...
No Matches
defer.h
Go to the documentation of this file.
1
8
9/*
10Copyright (c) 2026 MrXie1109
11
12Permission is hereby granted, free of charge, to any person obtaining a copy
13of this software and associated documentation files (the "Software"), to deal
14in the Software without restriction, including without limitation the rights
15to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16copies of the Software, and to permit persons to whom the Software is
17furnished to do so, subject to the following conditions:
18
19The above copyright notice and this permission notice shall be included in all
20copies or substantial portions of the Software.
21
22THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28SOFTWARE.
29*/
30
31#pragma once
32#include <type_traits>
33#include <utility>
34
35namespace console {
41 template <class F>
42 class DeferGuard {
43 F func;
44
45 public:
50 DeferGuard(const F &f) : func(f) {}
51
56 DeferGuard(F &&f) : func(std::move(f)) {}
57
62 };
63
69 template <class F>
71 return std::forward<F>(f);
72 }
73
74#ifndef CONSOLE_DEFER_NO_MACRO
75
76#define CONSOLE_CONCAT_IMPL(a, b) a##b
77
78#define CONSOLE_CONCAT(a, b) CONSOLE_CONCAT_IMPL(a, b)
79
91#define defer(...) \
92 auto CONSOLE_CONCAT(_dg_, __LINE__) = make_defer([&] { __VA_ARGS__; })
93
94#endif
95}
推迟执行的RAII守卫类。
Definition defer.h:42
DeferGuard(const F &f)
构造函数,接受推迟执行的函数。
Definition defer.h:50
F func
推迟执行的函数。
Definition defer.h:43
~DeferGuard()
析构函数,执行推迟执行的函数。
Definition defer.h:61
DeferGuard(F &&f)
构造函数,接受推迟执行的函数。
Definition defer.h:56
本库所有组件所在的顶层命名空间。
DeferGuard< typename std::decay< F >::type > make_defer(F &&f)
工厂函数,创建DeferGuard对象。
Definition defer.h:70