模板友谊 [英] Template friendship
问题描述
我尝试使用不同的模板参数访问模板类的受保护变量。带有模板参数的朋友声明会出现以下错误:
不允许使用多个模板参数列表
我的代码是
模板< class O_,class P_>
class MyClass {
//不允许多个模板参数列表
template< class R_> friend class MyClass< R_,P_>
//语法错误:template<
friend template< class R_> class MyClass< R_,P_>
public:
template< class R_>
ACopyConstructor(MyClass< R_,P_>& myclass):
SomeVariable(myclass.SomeVariable)
{}
protected:
O_ SomeVariable;
};
如果我删除了保护和好友声明,它会工作。
在你的情况下,如果你想成为与一个自由模板参数的实例化的朋友,你需要声明类的所有实例化模板作为朋友。
例如
A类,B类> friend class MyClass;
I'm trying to access protected variables of a template class with different template parameters. A friend declaration with template parameters is giving the following error:
multiple template parameter lists are not allowed
My code is
template<class O_, class P_>
class MyClass {
//multiple template parameter lists are not allowed
template<class R_> friend class MyClass<R_, P_>
//syntax error: template<
friend template<class R_> class MyClass<R_, P_>
public:
template<class R_>
ACopyConstructor(MyClass<R_, P_> &myclass) :
SomeVariable(myclass.SomeVariable)
{ }
protected:
O_ SomeVariable;
};
If I remove the protection and friend declaration it works.
From the standard: 14.5.3/9 [temp.friend], "A friend template shall not be declared partial specializations.", so you can only 'befriend' all instantiations of a class template or specific full specializations.
In your case, as you want to be friends with instantiations with one free template parameter, you need to declare the class template as a friend.
e.g.
template< class A, class B > friend class MyClass;
这篇关于模板友谊的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!