溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C++怎么避免使用通用名稱的高度不受限模板

發(fā)布時間:2021-11-24 11:03:51 來源:億速云 閱讀:95 作者:iii 欄目:大數(shù)據(jù)

本篇內容主要講解“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.

不受限的模板參數(shù)會完美匹配任何東西,因此這樣的模板可以覆蓋需要輕微轉換的特定類型。當使用ADL時,這種情況很麻煩/危險。通用的名稱會讓這個問題更容易發(fā)生。

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.

現(xiàn)在Bad中的==被設計用于引發(fā)問題,但是你能定位到實際代碼中的問題么?問題是v.size()返回一個無符號整數(shù),因此調用本地==時需要轉換;Bad中的==則不需要轉換。實際的類型,例如標準庫中的迭代器等有可能會表現(xiàn)出這種類似反社會問題的傾向。

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發(fā)現(xiàn)(就像示例代碼中發(fā)生的那樣。)。也就是說,它是高度可見的。

Note(注意)

This rule should not be necessary, but the committee cannot agree to exclude unconstrained templated from ADL.

本規(guī)則應該是沒有必要的,但是委員會不能同意將非受限模板從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.

不幸的是,這會引發(fā)很多假陽性;標準庫將很多非受限模板放入std命名空間,這導致大量違反本規(guī)則的情況。

Enforcement(實施建議)

Flag templates defined in a namespace where concrete types are also defined (maybe not feasible until we have concepts).

標記定義在和具體類型定義在同一命名空間的模板(也許只有通過concept才可能實現(xiàn))

到此,相信大家對“C++怎么避免使用通用名稱的高度不受限模板”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

c++
AI