您好,登錄后才能下訂單哦!
本篇內容主要講解“C++怎么避免使用通用名稱的高度不受限模板”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“C++怎么避免使用通用名稱的高度不受限模板”吧!
T.47:避免使用通用名稱的高度不受限模板
Reason(原因)
An unconstrained template argument is a perfect match for anything so such a template can be preferred over more specific types that require minor conversions. This is particularly annoying/dangerous when ADL is used. Common names make this problem more likely.
不受限的模板參數會完美匹配任何東西,因此這樣的模板可以覆蓋需要輕微轉換的特定類型。當使用ADL時,這種情況很麻煩/危險。通用的名稱會讓這個問題更容易發生。
Example(示例)
namespace Bad {
struct S { int m; };
template<typename T1, typename T2>
bool operator==(T1, T2) { cout << "Bad\n"; return true; }
}
namespace T0 {
bool operator==(int, Bad::S) { cout << "T0\n"; return true; } // compare to int
void test()
{
Bad::S bad{ 1 };
vector<int> v(10);
bool b = 1 == bad;
bool b2 = v.size() == bad;
}
}
This prints T0 and Bad.
代碼會打印T0和Bad。
Now the == in Bad was designed to cause trouble, but would you have spotted the problem in real code? The problem is that v.size() returns an unsigned integer so that a conversion is needed to call the local ==; the == in Bad requires no conversions. Realistic types, such as the standard-library iterators can be made to exhibit similar anti-social tendencies.
現在Bad中的==被設計用于引發問題,但是你能定位到實際代碼中的問題么?問題是v.size()返回一個無符號整數,因此調用本地==時需要轉換;Bad中的==則不需要轉換。實際的類型,例如標準庫中的迭代器等有可能會表現出這種類似反社會問題的傾向。
Note(注意)
If an unconstrained template is defined in the same namespace as a type, that unconstrained template can be found by ADL (as happened in the example). That is, it is highly visible.
如果不受限模板被定義在類型相同的命名空間,這個不受限模板可以被ADL發現(就像示例代碼中發生的那樣。)。也就是說,它是高度可見的。
Note(注意)
This rule should not be necessary, but the committee cannot agree to exclude unconstrained templated from ADL.
本規則應該是沒有必要的,但是委員會不能同意將非受限模板從ADL中排除出去。
Unfortunately this will get many false positives; the standard library violates this widely, by putting many unconstrained templates and types into the single namespace std.
不幸的是,這會引發很多假陽性;標準庫將很多非受限模板放入std命名空間,這導致大量違反本規則的情況。
Enforcement(實施建議)
Flag templates defined in a namespace where concrete types are also defined (maybe not feasible until we have concepts).
標記定義在和具體類型定義在同一命名空間的模板(也許只有通過concept才可能實現)
到此,相信大家對“C++怎么避免使用通用名稱的高度不受限模板”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。