C++核心準則C.165: 爲定製點使用using關鍵字

C.165: Use using for customization points

C.165: 爲定製點使用using關鍵字

 

Reason(原因)

To find function objects and functions defined in a separate namespace to "customize" a common function.

爲了發現那些爲了定製共通函數而定義於單獨的命名空間內的函數對象和函數。

 

Example(示例)

Consider swap. It is a general (standard-library) function with a definition that will work for just about any type. However, it is desirable to define specific swap()s for specific types. For example, the general swap() will copy the elements of two vectors being swapped, whereas a good specific implementation will not copy elements at all.

考慮交換函數。它是一個一般的(標準庫)可以適用於任何類型的函數。然而,也希望可以爲特殊類型定義特殊的交換函數。例如,通常的交換函數會複製作爲交換對象的vector的元素,然而好的特殊實現應該根本不復制元素。

namespace N {
    My_type X { /* ... */ };
    void swap(X&, X&);   // optimized swap for N::X
    // ...
}

void f1(N::X& a, N::X& b)
{
    std::swap(a, b);   // probably not what we wanted: calls std::swap()
}

The std::swap() in f1() does exactly what we asked it to do: it calls the swap() in namespace std. Unfortunately, that's probably not what we wanted. How do we get N::X considered?

函數f1中的std::swap()會準確執行我們所要求的:它調用std命名空間中的swap()。不幸的是那可能不是我們想要的。怎樣才能執行我們期待的N:X?

void f2(N::X& a, N::X& b)
{
    swap(a, b);   // calls N::swap
}

But that may not be what we wanted for generic code. There, we typically want the specific function if it exists and the general function if not. This is done by including the general function in the lookup for the function:

但是這樣(上面的代碼那樣,譯者注)做不是一般代碼中應該有的樣子。這裏我麼一般的想法是:如果存在特殊函數就執行它而不是一般函數。實現這種功能的方法就是將通用函數包含再函數的檢索範圍內。

 

void f3(N::X& a, N::X& b)
{
    using std::swap;  // make std::swap available
    swap(a, b);        // calls N::swap if it exists, otherwise std::swap
}

 

Enforcement(實施建議)

Unlikely, except for known customization points, such as swap. The problem is that the unqualified and qualified lookups both have uses.

不太可能實現。除非是已知的定製點,例如swap函數。問題是符合條件和不符合條件的查找都有用。

 

原文鏈接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c165-use-using-for-customization-points

 


 

覺得本文有幫助?歡迎點贊並分享給更多的人。

閱讀更多更新文章,請關注微信公衆號【面向對象思考】

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章