C++中using关键字​如何使用

发布时间:2021-07-23 15:16:56 作者:Leah
来源:亿速云 阅读:151

C++中using关键字如何使用,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

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
}

关于C++中using关键字如何使用问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

推荐阅读:
  1. c++中using
  2. using关键字

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

using c++

上一篇:synchronized 关键字的作用是什么

下一篇:PHP中final关键字有什么用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》