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.
其他選項:如果結果是一個值,而不是類型,使用常量表達式函數(shù)。
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
新書介紹
《實戰(zhàn)Python設計模式》是作者最近出版的新書,拜托多多關注!

本書利用Python 的標準GUI 工具包tkinter,通過可執(zhí)行的示例對23 個設計模式逐個進行說明。這樣一方面可以使讀者了解真實的軟件開發(fā)工作中每個設計模式的運用場景和想要解決的問題;另一方面通過對這些問題的解決過程進行說明,讓讀者明白在編寫代碼時如何判斷使用設計模式的利弊,并合理運用設計模式。
對設計模式感興趣而且希望隨學隨用的讀者通過本書可以快速跨越從理解到運用的門檻;希望學習Python GUI 編程的讀者可以將本書中的示例作為設計和開發(fā)的參考;使用Python 語言進行圖像分析、數(shù)據(jù)處理工作的讀者可以直接以本書中的示例為基礎,迅速構建自己的系統(tǒng)架構。
覺得本文有幫助?請分享給更多人。
關注微信公眾號【面向對象思考】輕松學習每一天!
面向對象開發(fā),面向對象思考!
