前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.165: 为定制点使用using关键字​

C++核心准则C.165: 为定制点使用using关键字​

作者头像
面向对象思考
发布2020-03-25 16:59:02
3910
发布2020-03-25 16:59:02
举报

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的元素,然而好的特殊实现应该根本不复制元素。

代码语言:javascript
复制
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?

代码语言:javascript
复制
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:

但是这样(上面的代码那样,译者注)做不是一般代码中应该有的样子。这里我么一般的想法是:如果存在特殊函数就执行它而不是一般函数。实现这种功能的方法就是将通用函数包含再函数的检索范围内。

代码语言:javascript
复制
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


觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-03-02,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • C.165: Use using for customization points
  • Reason(原因)
    • Enforcement(实施建议)
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档