前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则T.120:只在确实有需要时使用模板元编程

C++核心准则T.120:只在确实有需要时使用模板元编程

作者头像
面向对象思考
发布2020-09-28 16:38:39
4760
发布2020-09-28 16:38:39
举报
文章被收录于专栏:C++核心准则原文翻译

T.120: Use template metaprogramming only when you really need to

T.120:只在确实有需要时使用模板元编程

Reason(原因)

Template metaprogramming is hard to get right, slows down compilation, and is often very hard to maintain. However, there are real-world examples where template metaprogramming provides better performance than any alternative short of expert-level assembly code. Also, there are real-world examples where template metaprogramming expresses the fundamental ideas better than run-time code. For example, if you really need AST manipulation at compile time (e.g., for optional matrix operation folding) there might be no other way in C++.

模板元编程很难保证正确,拖慢编译过程,并且通常很难维护。然而,存在实际的例子:只要不是和专家编写的代码相比,模板就会提供比其他选项更好的性能。同时,存在实际的例子模板元编程比实时代码更好地说明基本想法。例如,如果你真的需要在编译时AST操作(例如,为了可选的矩阵折叠),C++中应该没有其他方式。

Example, bad(反面示例)

Example, bad(反面示例)
代码语言:javascript
复制
enable_if

Instead, use concepts. But see How to emulate concepts if you don't have language support.

可以使用概念代替。但是需要参照【使用模板元编程模仿概念】

Example(示例)

代码语言:javascript
复制
good

Alternative: If the result is a value, rather than a type, use a constexpr function.

其他选项:如果结果是一个值,而不是类型,使用常量表达式函数。

Note(注意)

If you feel the need to hide your template metaprogramming in macros, you have probably gone too far.

如果你觉得你需要使用宏来隐藏模板元编程,你可能已经走得更远了。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t120-use-template-metaprogramming-only-when-you-really-need-to

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-09-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Reason(原因)
    • Example, bad(反面示例)
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档