首页 文章详情

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

面向对象思考 | 429 2020-09-24 05:16 0 0 0
UniSMS (合一短信)

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(反面示例)
enable_if

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

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


Example(示例)

??? 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


新书介绍

《实战Python设计模式》是作者最近出版的新书,拜托多多关注!

本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。




觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!



good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter