How to access private members of other template cl

2019-05-07 11:15发布

This question already has an answer here:

This extremely minimal example will fail to compile because A<int> cannot access the private member i in A<double>

template <class T>
class A {
    int i;
  public:
    template <class U>
    void copy_i_from( const A<U> & a ){
        i = a.i;
    }
};

int main(void) {
    A<int> ai;
    A<double> ad;
    ai.copy_i_from(ad);
    return 0;
}

I cannot find the correct way to make those template instances friends.

1条回答
虎瘦雄心在
2楼-- · 2019-05-07 11:33
template <class T>
class A {
    template<class U>
    friend class A;
    int i;
  public:
    template <class U>
    void copy_i_from( const A<U> & a ){
        i = a.i;
    }
};

int main(void) {
    A<int> ai;
    A<double> ad;
    ai.copy_i_from(ad);
    return 0;
}
查看更多
登录 后发表回答