Template friendship

怎甘沉沦 提交于 2019-12-17 16:46:12

问题


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.


回答1:


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;



回答2:


The following seems to be working, effectively declaring all MyClass types to be friend with each other.

template<class O_, class P_> 
class MyClass {
    template<class R_, class P_> friend class MyClass;

public:
    template<class R_>
    ACopyConstructor(MyClass<R_, P_> &myclass) :
       SomeVariable(myclass.SomeVariable)
    { }

protected:
    O_ SomeVariable;
};


来源:https://stackoverflow.com/questions/1458752/template-friendship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!