C++ 實現Golang裡的defer

斌好菜發表於2018-11-13

不多說了,直接貼程式碼。就一個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 Studio2017CommunityCommon7IDEVCSnippets2052Visual C++目錄。

這個目錄可以在vs的 工具-程式碼片段管理器 就可以找到。

完畢!!!

相關文章