不多说了,直接贴代码。就一个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的 工具-代码片段管理器 就可以找到。

完毕!!!

最新文章

  1. 使用backbone的history管理SPA应用的url
  2. npm start 作用
  3. SQL语句 - MERGE INTO 、Cross/Outer Apply用法理解
  4. php变量赋值给js
  5. Http 请求处理流程
  6. java netty之ServerBootstrap的启动
  7. lua对模块接口扩展的一种方法
  8. linux 命令之系统活动报告sar
  9. hdu 5091(线段树+扫描线)
  10. ASP.NET通用权限组件思路设计
  11. 在mac系统安装Apache Tomcat的详细步骤(转载自himi的博客,修改了错误添加了图片)
  12. sqlcmd的使用小结
  13. PHP实现中文字符串截取无乱码
  14. CCPC2017湘潭 1263 1264 1267 1268
  15. 原生js--insertAdjacentHTML
  16. php 解析xml
  17. div 画园
  18. matlab读图函数
  19. checkbox中把选项文字与小圆圈关联上
  20. c# webapi2 实用详解

热门文章

  1. ROUND function and arithmetic overflow
  2. hdoj--1872--稳定排序(水题)
  3. Chapter 4 Syntax Analysis
  4. npm 是干什么的?
  5. openssh常用命令记录
  6. CodeForces 731C Socks (DFS或并查集)
  7. Python网咯爬虫 — Scrapy框架应用
  8. bzoj 1639: [Usaco2007 Mar]Monthly Expense 月度开支【二分】
  9. C#将类对象转换为字典
  10. 【[转】MySql模糊查询