11

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.

DarioP
  • 5,377
  • 1
  • 33
  • 52
  • 1
    `A` and `A` are completely different classes. Consequently, rightfully they can't access mutually each others private members. – 101010 Oct 17 '14 at 09:39
  • 1
    @40two Sure, the point is how to let them with some kind of friend declaration. – DarioP Oct 17 '14 at 09:41

1 Answers1

17
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;
}
101010
  • 41,839
  • 11
  • 94
  • 168