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


觉得本文有帮助?欢迎点赞并分享给更多的人。

阅读更多更新文章,请关注微信公众号【面向对象思考】

原创文章 414 获赞 724 访问量 35万+

猜你喜欢

转载自blog.csdn.net/craftsman1970/article/details/105775329