溫馨提示×

溫馨提示×

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

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

C+為什么避免定義沒有明確語義的概念

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

本篇內(nèi)容介紹了“C+為什么避免定義沒有明確語義的概念”的有關(guān)知識,在實(shí)際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

T.20:避免定義沒有明確語義的“概念”

Reason(原因)

Concepts are meant to express semantic notions, such as "a number", "a range" of elements, and "totally ordered." Simple constraints, such as "has a + operator" and "has a > operator" cannot be meaningfully specified in isolation and should be used only as building blocks for meaningful concepts, rather than in user code.

概念意在表現(xiàn)某種有語義的觀念,例如“數(shù)字”,元素的“范圍”,和“完全有序”等。簡單的約束,例如有+運(yùn)算符,有>運(yùn)算符不能算作被獨(dú)立,明確地定義,只應(yīng)用于某個明確概念的組成部分,而不是在代碼中直接使用。

Example, bad (using TS concepts)

反面示例(使用TS概念)

template<typename T>
concept Addable = has_plus<T>;    // bad; insufficient

template<Addable N> auto algo(const N& a, const N& b) // use two numbers
{
   // ...
   return a + b;
}

int x = 7;
int y = 9;
auto z = algo(x, y);   // z = 16

string xx = "7";
string yy = "9";
auto zz = algo(xx, yy);   // zz = "79"

Maybe the concatenation was expected. More likely, it was an accident. Defining minus equivalently would give dramatically different sets of accepted types. This Addable violates the mathematical rule that addition is supposed to be commutative: a+b == b+a.

也許期待的操作就是連結(jié)。更有可能的是,這只是一個意外。對等地定義減操作將會提供一套明顯不同的可接受類型。這個可加性違反了加法運(yùn)算滿足交換律(a+b==b+a)這個規(guī)則。

Note(注意)

The ability to specify a meaningful semantics is a defining characteristic of a true concept, as opposed to a syntactic constraint.

定義明確語義的能力是真正的概念所具備的明確特征,而不是句法約束。

Example (using TS concepts)

示例(使用TS概念)

template<typename T>
// The operators +, -, *, and / for a number are assumed to follow the usual mathematical rules
concept Number = has_plus<T>
                && has_minus<T>
                && has_multiply<T>
                && has_divide<T>;

template<Number N> auto algo(const N& a, const N& b)
{
   // ...
   return a + b;
}

int x = 7;
int y = 9;
auto z = algo(x, y);   // z = 16

string xx = "7";
string yy = "9";
auto zz = algo(xx, yy);   // error: string is not a Number
Note(注意)

Concepts with multiple operations have far lower chance of accidentally matching a type than a single-operation concept.

相比只有一個操作的概念,包含多個操作的概念偶然和某個類型匹配的可能性會大為降低。

Enforcement(實(shí)施建議)

  • Flag single-operation concepts when used outside the definition of other concepts.

  • 標(biāo)記處于其他概念定義范圍之外的單操作概念。

  • Flag uses of enable_if that appears to simulate single-operation concepts.

  • 標(biāo)記將enable_if用于模擬單操作概念的情況。

“C+為什么避免定義沒有明確語義的概念”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問一下細(xì)節(jié)

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

c++
AI