lundi 18 mars 2019

How can I have templated friends?

I have two parametrized classes, and want to transfer private information between them. Two attempts:

template<int I> class athing;

template<int J> class bthing {
  int data[J];
 public:
  template<int I> friend void athing<I>::transfer(const bthing &);
  template<int I> friend void staticxfer(athing<I> &, const bthing &);
};

template<int I> class athing {
  int data[I];
 public:
  template<int J> void transfer(const bthing<J> &a) {
    data[0] = a.data[0];
  }
  template<int J> friend void staticxfer(athing &a, const bthing<J> &b) {
    a.data[0] = b.data[0];
  }
};

int main() {
  athing<10> a;
  bthing<10> b;

  a.transfer(b);
  staticxfer(a, b);
}

The member-method one (transfer) causes the error warning: dependent nested name specifier 'athing<I>::' for friend class declaration is not supported; turning off access control for 'bthing' [-Wunsupported-friend] (not an error, but transfer was not granted friendship) while the non-member method one (staticxfer) causes the error error: call to 'staticxfer' is ambiguous (which for me is weird: I want staticxfer to be friends of athing and bthing, friendship should be cumulative, not ambiguous).

What is the clean way to do this?

(of course this is a toy bit of code; in practice, I have 7 different parameterized classes, and want to transfer data from any one to any other one, doing non-trivial modifications on the data and using private functions of both).

Aucun commentaire:

Enregistrer un commentaire