您好,登錄后才能下訂單哦!
本篇內容介紹了“C+為什么避免定義沒有明確語義的概念”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
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.
概念意在表現某種有語義的觀念,例如“數字”,元素的“范圍”,和“完全有序”等。簡單的約束,例如有+運算符,有>運算符不能算作被獨立,明確地定義,只應用于某個明確概念的組成部分,而不是在代碼中直接使用。
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.
也許期待的操作就是連結。更有可能的是,這只是一個意外。對等地定義減操作將會提供一套明顯不同的可接受類型。這個可加性違反了加法運算滿足交換律(a+b==b+a)這個規則。
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
Concepts with multiple operations have far lower chance of accidentally matching a type than a single-operation concept.
相比只有一個操作的概念,包含多個操作的概念偶然和某個類型匹配的可能性會大為降低。
Enforcement(實施建議)
Flag single-operation concepts when used outside the definition of other concepts.
標記處于其他概念定義范圍之外的單操作概念。
Flag uses of enable_if that appears to simulate single-operation concepts.
標記將enable_if用于模擬單操作概念的情況。
“C+為什么避免定義沒有明確語義的概念”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。