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

时间:2022-07-26
本文章向大家介绍C++核心准则T.120:只在确实有需要时使用模板元编程,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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