经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C » 查看文章
C++ 实现Golang里的defer
来源:cnblogs  作者:斌好菜  时间:2018/11/14 10:03:48  对本文有异议

不多说了,直接贴代码。就一个hpp文件。

  1. 1 #include <functional>
  2. 2
  3. 3 #define CONCAT_(a, b) a##b
  4. 4 #define CONCAT(a, b) CONCAT_(a,b)
  5. 5 /*
  6. 6 eg. defer(代码); 注意后面 一定要加上 ;
  7. 7 */
  8. 8
  9. 9 #define defer(code) DeferOp CONCAT(_defer_, __LINE__) = [&](){code}
  10. 10
  11. 11 class DeferOp
  12. 12 {
  13. 13 public:
  14. 14 DeferOp(std::function<void()>&& fn)
  15. 15 : m_fun(std::move(fn))
  16. 16 {}
  17. 17 ~DeferOp()
  18. 18 {
  19. 19 if (nullptr != m_fun)
  20. 20 {
  21. 21 m_fun();
  22. 22 }
  23. 23 }
  24. 24
  25. 25 #if _MSC_VER >= 1700 //VS2012
  26. 26 DeferOp(DeferOp &&other) = delete;
  27. 27 DeferOp(const DeferOp&) = delete;
  28. 28 void operator=(const DeferOp &) = delete;
  29. 29 #else
  30. 30 DeferOp(DeferOp &&other);
  31. 31 DeferOp(const DeferOp&);
  32. 32 void operator=(const DeferOp &);
  33. 33 #endif
  34. 34 protected:
  35. 35 std::function<void()> m_fun;
  36. 36 };

使用方法:

  1. 1 {
  2. 2 defer
  3. 3 (
  4. 4 //代码
  5. 5 );
  6. 6 }

再加个 vs 代码片段

  1. 1 <?xml version="1.0" encoding="utf-8"?>
  2. 2 <CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  3. 3 <CodeSnippet Format="1.0.0">
  4. 4 <Header>
  5. 5 <Title>defer</Title>
  6. 6 <Shortcut>defer</Shortcut>
  7. 7 <Description>延迟的代码片段</Description>
  8. 8 <Author>bin432</Author>
  9. 9 <SnippetTypes>
  10. 10 <SnippetType>Expansion</SnippetType>
  11. 11 <SnippetType>SurroundsWith</SnippetType>
  12. 12 </SnippetTypes>
  13. 13 </Header>
  14. 14 <Snippet>
  15. 15 <Declarations>
  16. 16 <Literal>
  17. 17
  18. 18 </Literal>
  19. 19 </Declarations>
  20. 20 <Code Language="cpp"><![CDATA[defer
  21. 21 (
  22. 22 $selected$ $end$
  23. 23 );]]>
  24. 24 </Code>
  25. 25 </Snippet>
  26. 26 </CodeSnippet>
  27. 27 </CodeSnippets>

保存为defer.snippet文件,放到C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\Snippets\2052\Visual C++目录。

这个目录可以在vs的 工具-代码片段管理器 就可以找到。

完毕!!!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号