C++核心準(zhǔn)則C.165: 為定制點(diǎn)使用using關(guān)鍵字?

C.165: Use?using?for customization points
C.165: 為定制點(diǎn)使用using關(guān)鍵字
Reason(原因)
To find function objects and functions defined in a separate namespace to "customize" a common function.
為了發(fā)現(xiàn)那些為了定制共通函數(shù)而定義于單獨(dú)的命名空間內(nèi)的函數(shù)對(duì)象和函數(shù)。
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.
考慮交換函數(shù)。它是一個(gè)一般的(標(biāo)準(zhǔn)庫(kù))可以適用于任何類型的函數(shù)。然而,也希望可以為特殊類型定義特殊的交換函數(shù)。例如,通常的交換函數(shù)會(huì)復(fù)制作為交換對(duì)象的vector的元素,然而好的特殊實(shí)現(xiàn)應(yīng)該根本不復(fù)制元素。
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?
函數(shù)f1中的std::swap()會(huì)準(zhǔn)確執(zhí)行我們所要求的:它調(diào)用std命名空間中的swap()。不幸的是那可能不是我們想要的。怎樣才能執(zhí)行我們期待的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:
但是這樣(上面的代碼那樣,譯者注)做不是一般代碼中應(yīng)該有的樣子。這里我么一般的想法是:如果存在特殊函數(shù)就執(zhí)行它而不是一般函數(shù)。實(shí)現(xiàn)這種功能的方法就是將通用函數(shù)包含再函數(shù)的檢索范圍內(nèi)。
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(實(shí)施建議)
Unlikely, except for known customization points, such as?swap. The problem is that the unqualified and qualified lookups both have uses.
不太可能實(shí)現(xiàn)。除非是已知的定制點(diǎn),例如swap函數(shù)。問題是符合條件和不符合條件的查找都有用。
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c165-use-using-for-customization-points
覺得本文有幫助?請(qǐng)分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
