有没有办法std::swap
为私有类专门化一个函数(比如,)?
例如,当我测试这个时:
#include <algorithm>
class Outer
{
struct Inner
{
int a;
void swap(Inner &other)
{
using std::swap;
swap(this->a, other.a);
}
};
public:
static void test();
};
namespace std
{
template<> void swap<Outer::Inner>(Outer::Inner &a, Outer::Inner &b)
{ a.swap(b); }
}
void Outer::test()
{
using std::swap;
Inner a, b;
swap(a, b);
}
int main()
{
Outer::test();
return 0;
}
我明白了:
Test.cpp:20:47: error: 'Inner' is a private member of 'Outer'
template<> void swap<Outer::Inner>(Outer::Inner &a, Outer::Inner &b)
^
Test.cpp:5:12: note: implicitly declared private here
struct Inner
^
Test.cpp:20:64: error: 'Inner' is a private member of 'Outer'
template<> void swap<Outer::Inner>(Outer::Inner &a, Outer::Inner &b)
^
Test.cpp:5:12: note: implicitly declared private here
struct Inner
^
Test.cpp:20:33: error: 'Inner' is a private member of 'Outer'
template<> void swap<Outer::Inner>(Outer::Inner &a, Outer::Inner &b)
^
Test.cpp:5:12: note: implicitly declared private here
struct Inner
(我确实意识到声明swap
可以通过 ADL 找到的朋友可以避免这个问题swap
,但这与我的问题无关。swap
只是一个例子。)