您好,登錄后才能下訂單哦!
這篇文章主要介紹“C++中為什么不要過度參數化”,在日常操作中,相信很多人在C++中為什么不要過度參數化問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”C++中為什么不要過度參數化”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
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 A
T 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這個縮寫描述了一些看起來錯誤(看起來被沖突的參數約束),但實際上可以和正確的實現一起工作(由于最小化的依賴關系而不會被沖突所限制)的賦值和初始化。”
Enforcement(實施建議)
Flag member types that do not depend on every template argument
標記不依賴于任何模板參數的成員
Flag member functions that do not depend on every template argument
標記不依賴于任何模板參數的成員的成員函數。
到此,關于“C++中為什么不要過度參數化”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。