c++ - 我应该专门化或重载在 `std::swap` 之类的命名空间中定义的模板吗?

标签 c++ overloading swap

如果我有一些管理资源的类类型,例如,我的类需要定义一个 swap()作为其接口(interface)的一部分,该接口(interface)适用于该类型的对象,那么我通常会这样做:

struct Foo{};

Foo f1, f2;

void swap(Foo& lhs, Foo& rhs){
    // code to swap member data of lhs and rhs
}

int main(){
    using std::swap;
    Foo f1, f2;
    swap(f1, f2);
}
  • 现在,我是否重载了std::swap ,还是专攻呢?
  • 我了解到,如果我想专门化标准库的函数/类模板,那么我应该打开命名空间 std并在那里声明专业。例如:

  • namespace std{
        void swap(Foo&, Foo&);
    }
    
  • 我记得专精的时候std::hash对于我打算用作无序关联容器的元素类型的类型,例如 std::unordered_map , 我是专业的 std::hash这样:

  • namespace std{ // opening namespace std
        template<>
        class hash<Foo>{
              //...
        };
    }
    
    那么,这是正确的吗?我应该重载还是特化std::swap ?

    最佳答案

    该标准通常不允许在命名空间 std 中添加重载或特化。 :

    [namespace.std]/1 Unless otherwise specified, the behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std.


    专门化类模板有一个异常(exception)。您的 std::hash<Foo>示例属于:

    [namespace.std]/2 Unless explicitly prohibited, a program may add a template specialization for any standard library class template to namespace std provided that (a) the added declaration depends on at least one program-defined type and (b) the specialization meets the standard library requirements for the original template.


    您可以重载某些标准库函数 命名空间 std ,依靠 ADL 找到它们:

    [namespace.std]/7 Other than in namespace std or in a namespace within namespace std, a program may provide an overload for any library function template designated as a customization point, provided that (a) the overload’s declaration depends on at least one user-defined type and (b) the overload meets the standard library requirements for the customization point. [Note: This permits a (qualified or unqualified) call to the customization point to invoke the most appropriate overload for the given arguments. —end note]

    std::swap实际上是一个定制点。

    关于c++ - 我应该专门化或重载在 `std::swap` 之类的命名空间中定义的模板吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66947575/

    相关文章:

    c++ - 使用多个排序标准对对象 vector 进行排序

    c - 将第一个数字与第二个数字交换,将第二个数字与第三个数字交换,等等

    java - 如何使用 JConsole 分析交换空间

    c++ - 禁止模板虚函数是一种不必要的谨慎吗?

    c++ - 在Geant4中找到参与nCapture过程的核

    typescript - 如何让函数传递具有相同重载的参数?

    c - 在 C 中交换 2 个数组时的困难

    c++ - 我无法使用 C++ 访问类的属性

    c++ - 是否有平面未排序的 map /集合实现?

    c++ - 当重载方法将模板类作为参数时会发生什么