How to access private members of other template cl

2019-05-07 11:28发布

问题:

This question already has an answer here:

  • How to share protected members between C++ template classes? 1 answer

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:

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;
}