我正在实现一个与 std::array
具有类似接口(interface)的类,它同时具有 member swap()
和 non-member swap()
.
由于我希望我的类模仿标准容器,因此我想实现两种 swap()
(非成员 swap()
是通过ADL,因为不允许专门化 std::swap()
):
class A {
public:
friend void swap(A& a, A& b) { /* swap the stuff */ }
void swap(A& other) { swap(*this, other); }
};
但是,似乎我无法从类内部调用非成员 swap()
,因为它更喜欢成员 swap()
即使它只有一个参数。将其更改为 ::swap(*this, other)
也不起作用,因为类内友元函数只能通过 ADL 找到。我如何从类内部调用非成员 swap()
?
最佳答案
问题是成员函数swap
的名称隐藏了A::swap
主体中的命名空间范围swap
。在 A::swap
中对 swap
进行非限定名称查找将永远找不到命名空间范围 swap
,因此,命名空间范围 swap
不会成为重载集的一部分。解决这个问题的一种方法是简单地在 A::swap
主体中添加命名空间范围 swap
的声明:
class A
{
public:
friend void swap(A& a, A& b) { /* swap the stuff */ }
void swap(A& other)
{
void swap(A& a, A& b);
swap(*this, other);
}
};
话虽这么说,我不确定这对你到底有什么作用。显而易见的解决方案是仅根据 A::swap
实现 namespace 范围 swap
,而不是相反。就我个人而言,我一开始就没有 swap
成员函数。 The typical way of swapping a
和b
只是交换(a, b)
...
关于c++ - 根据非成员 swap() 实现成员 swap(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59564137/