gk-auto 发表于 2021-4-3 12:13:15

使用using关键字选择定制或通用函数

https://p1-tt.byteimg.com/origin/pgc-image/3acccdb957f749d299701850e96c941b?from=pc

C.165: Use using for customization pointsC.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

wxz_100 发表于 2021-4-3 12:13:16

真是被感动的痛哭流涕……

twk2019 发表于 2021-4-3 12:19:41

无私奉献,好工控人,32个赞送给你!!

邓日龙_R78NP 发表于 2025-11-14 17:15:52

学到了学到了,这波分享太实用啦!

zhengliu20 发表于 2025-11-14 19:10:38

这逻辑绝了,分析得太到位了吧

牛角兄弟 发表于 2025-11-14 22:03:03

路过打卡,为优质内容疯狂打 call

刘烁_n2e60 发表于 2025-11-14 23:08:02

蹲个后续,楼主记得更新呀,在线等挺急的~

折飞 发表于 2025-11-15 14:02:59

理性围观,感觉大家说的都有道理~

无名小卒 发表于 2025-11-15 14:12:48

画面感太强了,仿佛身临其境!

198366809 发表于 2025-11-15 14:13:01

水个经验,支持楼主,加油呀
页: [1] 2
查看完整版本: 使用using关键字选择定制或通用函数