非专业化模板中模板专业化的成员访问权限
Member access of template specialisation in unspecialised template
以下代码编译失败(使用clang(:
template<int N>
class Foo {
public:
Foo() : value(N) { }
void getValue(Foo<1>& foo)
{
value = foo.value;
}
protected:
int value;
};
int main(int argc, const char * argv[])
{
Foo<1> fooOne = Foo<1>();
Foo<2> fooTwo = Foo<2>();
fooTwo.getValue(fooOne);
return 0;
}
错误为main.cpp:21:15: error: 'value' is a protected member of 'Foo<1>'
。这一切都很好。
我的问题是有没有办法使用朋友来实现这一点?例如,下面的代码会产生同样的错误,但我希望它能起作用。
template<int N>
class Foo {
public:
Foo() : value(N) { }
friend class Foo<1>;
void getValue(Foo<1>& foo)
{
value = foo.value;
}
protected:
int value;
};
当然,我可能非常可怕,并在访问模板参数的受保护成员或http://www.gotw.ca/gotw/076.htm.但我宁愿不要为了一些我可能只是很密集的事情而诉诸那种程度的技巧。
您的friend
方式不对。Foo<N>
需要成为Foo<1>
的朋友,因为它需要访问Foo<1>
的内部;您正在使Foo<1>
成为Foo<N>
的friend
。为了简单起见,您可以只friend
所有这些:
template <int N>
class Foo {
// mass inter-Foo friendship
template <int > friend class Foo;
// rest as you had before
};
相关文章:
- 通过方法访问结构
- 如何使用默认参数等选择模板专业化
- 使用不带参数的函数访问结构元素
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- 用于访问容器<T>数据成员的正确 API
- 访问者访问变体并返回不同类型时出错
- 尝试通过多个向量访问变量时,向量下标超出范围
- 无法访问嵌套类.类的使用无效
- Lambda 函数,用于调用有权访问类成员的成员函数
- 从特定专业化继承时可访问的模板基类?
- 使用QtCreator,如何在我有权访问ssh的远程服务器上构建我的项目?
- 如何访问相同特征C 的不同性状专业化
- 默认赋值运算符有权访问基类的私有成员
- 成员功能模板专业化是否可以具有与主模板不同的访问级别
- 外部必须有权访问类构造函数
- 检查用户名是否有权访问窗口上的文件夹
- 通过模板专业化获得对类成员的访问权限
- 获取从基类指针到具有不同类型的两个派生成员变量的访问权
- 好友有权访问好友的成员,但似乎无法更新好友的成员
- 非专业化模板中模板专业化的成员访问权限