如果我有一些管理资源的类类型,例如,我的类需要定义一个 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 namespacestd
.
专门化类模板有一个异常(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 namespacestd
, 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/