C++ 实现Golang里的defer
2024-08-31 22:01:43
不多说了,直接贴代码。就一个hpp文件。
1 #include <functional>
2
3 #define CONCAT_(a, b) a##b
4 #define CONCAT(a, b) CONCAT_(a,b)
5 /*
6 eg. defer(代码); 注意后面 一定要加上 ;
7 */
8
9 #define defer(code) DeferOp CONCAT(_defer_, __LINE__) = [&](){code}
10
11 class DeferOp
12 {
13 public:
14 DeferOp(std::function<void()>&& fn)
15 : m_fun(std::move(fn))
16 {}
17 ~DeferOp()
18 {
19 if (nullptr != m_fun)
20 {
21 m_fun();
22 }
23 }
24
25 #if _MSC_VER >= 1700 //VS2012
26 DeferOp(DeferOp &&other) = delete;
27 DeferOp(const DeferOp&) = delete;
28 void operator=(const DeferOp &) = delete;
29 #else
30 DeferOp(DeferOp &&other);
31 DeferOp(const DeferOp&);
32 void operator=(const DeferOp &);
33 #endif
34 protected:
35 std::function<void()> m_fun;
36 };
使用方法:
1 {
2 defer
3 (
4 //代码
5 );
6 }
再加个 vs 代码片段
1 <?xml version="1.0" encoding="utf-8"?>
2 <CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
3 <CodeSnippet Format="1.0.0">
4 <Header>
5 <Title>defer</Title>
6 <Shortcut>defer</Shortcut>
7 <Description>延迟的代码片段</Description>
8 <Author>bin432</Author>
9 <SnippetTypes>
10 <SnippetType>Expansion</SnippetType>
11 <SnippetType>SurroundsWith</SnippetType>
12 </SnippetTypes>
13 </Header>
14 <Snippet>
15 <Declarations>
16 <Literal>
17
18 </Literal>
19 </Declarations>
20 <Code Language="cpp"><![CDATA[defer
21 (
22 $selected$ $end$
23 );]]>
24 </Code>
25 </Snippet>
26 </CodeSnippet>
27 </CodeSnippets>
保存为defer.snippet文件,放到C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\Snippets\2052\Visual C++目录。
这个目录可以在vs的 工具-代码片段管理器 就可以找到。
完毕!!!
最新文章
- 使用backbone的history管理SPA应用的url
- npm start 作用
- SQL语句 - MERGE INTO 、Cross/Outer Apply用法理解
- php变量赋值给js
- Http 请求处理流程
- java netty之ServerBootstrap的启动
- lua对模块接口扩展的一种方法
- linux 命令之系统活动报告sar
- hdu 5091(线段树+扫描线)
- ASP.NET通用权限组件思路设计
- 在mac系统安装Apache Tomcat的详细步骤(转载自himi的博客,修改了错误添加了图片)
- sqlcmd的使用小结
- PHP实现中文字符串截取无乱码
- CCPC2017湘潭 1263 1264 1267 1268
- 原生js--insertAdjacentHTML
- php 解析xml
- div 画园
- matlab读图函数
- checkbox中把选项文字与小圆圈关联上
- c# webapi2 实用详解