C++核心准则T.61:不要过度参数化成员(SCARY)
T.61: Do not over-parameterize members (SCARY)
T.61:不要過度參數化成員(SCARY)
?
Reason(原因)
A member that does not depend on a template parameter cannot be used except for a specific template argument. This limits use and typically increases code size.
不依賴于模板參數的成員無法使用,特定的模板參數除外。這會限制使用并通常會增加代碼大小。
?
Example, bad(反面示例)
template<typename T, typename A = std::allocator{}>// requires Regular<T> && Allocator<A> class List { public:struct Link { // does not depend on AT elem;T* pre;T* suc;};using iterator = Link*;iterator first() const { return head; }// ... private:Link* head; };List<int> lst1; List<int, My_allocator> lst2;This looks innocent enough, but now?Link?formally depends on the allocator (even though it doesn't use the allocator). This forces redundant instantiations that can be surprisingly costly in some real-world scenarios. Typically, the solution is to make what would have been a nested class non-local, with its own minimal set of template parameters.
代碼看起來足夠正確,但是現在Link形式上依賴于分配器(即使它沒有使用分配器)。這會引發多余的例示,而這種例示在某些現實流程中可能會帶來令人驚訝的高成本。通常的解決方案是讓本來的嵌套類別弄成非局部的,同時它的成員只擁有最少的模板參數。
template<typename T> struct Link {T elem;T* pre;T* suc; };template<typename T, typename A = std::allocator{}>// requires Regular<T> && Allocator<A> class List2 { public:using iterator = Link<T>*;iterator first() const { return head; }// ... private:Link* head; };List<int> lst1; List<int, My_allocator> lst2;Some people found the idea that the?Link?no longer was hidden inside the list scary, so we named the technique?SCARY. From that academic paper: "The acronym SCARY describes assignments and initializations that are Seemingly erroneous (appearing Constrained by conflicting generic parameters), but Actually work with the Right implementation (unconstrained bY the conflict due to minimized dependencies)."
有些人會發現Link不再被list隱藏,因此我們稱這種技術為SCARY。根據大學論文:“SCARY這個縮寫描述了一些看起來錯誤(看起來被沖突的參數約束),但實際上可以和正確的實現一起工作(由于最小化的依賴關系而不會被沖突所限制)的賦值和初始化。”
論文鏈接:
http://www.open-std.org/jtc1/sc22/WG21/docs/papers/2009/n2911.pdf
?
Enforcement(實施建議)
-
Flag member types that do not depend on every template argument
-
標記不依賴于任何模板參數的成員
-
Flag member functions that do not depend on every template argument
-
標記不依賴于任何模板參數的成員的成員函數。
?
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t61-do-not-over-parameterize-members-scary
?
新書介紹
《實戰Python設計模式》是作者最近出版的新書,拜托多多關注!
本書利用Python 的標準GUI 工具包tkinter,通過可執行的示例對23 個設計模式逐個進行說明。這樣一方面可以使讀者了解真實的軟件開發工作中每個設計模式的運用場景和想要解決的問題;另一方面通過對這些問題的解決過程進行說明,讓讀者明白在編寫代碼時如何判斷使用設計模式的利弊,并合理運用設計模式。
對設計模式感興趣而且希望隨學隨用的讀者通過本書可以快速跨越從理解到運用的門檻;希望學習Python GUI 編程的讀者可以將本書中的示例作為設計和開發的參考;使用Python 語言進行圖像分析、數據處理工作的讀者可以直接以本書中的示例為基礎,迅速構建自己的系統架構。
?
?
覺得本文有幫助?請分享給更多人。
關注微信公眾號【面向對象思考】輕松學習每一天!
面向對象開發,面向對象思考!
?
?
總結
以上是生活随笔為你收集整理的C++核心准则T.61:不要过度参数化成员(SCARY)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【FXCG】美联储加息之际,新兴市场加息
- 下一篇: linux机顶盒界面,基于嵌入式Linu