declaring a friend template function

57 views Asked by At

This question is based on partially on exercise 15-4 in Accelerated C++ [1] and the code in that book. I want to declare the myclone function as a friend of a class so that it has access to private members. The myclone function is declared as a template, but I don't want to give all possible functions access to the private members, only those associated with that class.

class A{
    template <class T>
    friend T* myclone(const T*);

    A* clone() const {return new A(*this);}
}

some other file:

template <class T>
T* myclone(const T* t) {return t->clone();}

Another hypothetical myclone function could call the clone method of an A object, but I want to restrict the private access to A* myclone(const A*). Is there a way to do this or am I overthinking it, and this situation would never occur in practice? Should I use a template specialization?

[1] Koenig, A., & Moo, B. E. (2000). Accelerated C++ Practical Programming by Example. Pearson.

1

There are 1 answers

1
n. m. could be an AI On

You cannot give a friend access to only some of your private parts. It's an all or nothing thing.

friend A* myclone(const A*); doesn't work because there is no such function. The template isn't that function, nor any of its specialization is. If you want to befriend a particular specialization, just say so:

template <class T> T* myclone(const T*); // needs to be declared first

class A {
   friend A* myclone<A>(const A*);
   ...