【发布时间】:2013-08-20 21:22:26
【问题描述】:
有没有办法为私有类专门化一个函数(例如,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
(我确实意识到声明可以通过 ADL 找到的朋友 swap 可以避免 swap 的这个问题,但这与我的问题无关。swap 只是一个示例。)
【问题讨论】:
-
将
friend void swap(Inner, Inner)放入Outer? -
@TemplateRex:这不会专门化
std::swap,它只是一个名为swap的非成员函数。 -
你不能专门化一个不可见的类。由于
struct被声明为具有私有访问权限,因此只有Outer可以看到它。因此,您不能创建可以看到它的非外部成员函数 - 阻止您专门化它。 -
@ZacHowland:例如,有没有办法将其声明为
friend?我觉得应该有,但我找不到任何有效的语法......而且我不明白为什么它不应该是可能的。 -
@Mehrdad 下一次尝试:朋友声明侧外。查看更新的答案。
标签: c++ private friend template-specialization specialization