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