Search code examples
c++templatesfriend

Declare many functions as friends of a class


How to conveniently declare many template functions as friend function of a template class?

Example:

template <typename T>
void funct1(MyClass<T> & A); //1.forward declaration.

template <typename T>
class MyClass{
    protected:
    T a;
    friend funct1(MyClass<T> & A); //2.declare friend
}
template <typename T>
void funct1(MyClass<T> & A){ //3.actual implementation
    ++A.a;
}

step 1,2,3 get repeated for each of the many functions....

Is it possible to group all these function into something, then declare everything in that something are friends of the template class?


Solution

  • How about A friend class, all the functions can go into that one friend class:

    #include <iostream>
    
    using namespace std;
    
    template <typename T>
    class MyFriend;
    
    template <typename T>
    class MyClass{
        protected:
          T a;
        public:
          MyClass(T _a):a(_a) {}
    
        friend MyFriend<T>;
    };
    
    template <typename T>
    class MyFriend {
      public:
      void funct1(MyClass<T> &A) {
        ++A.a;
        cout << "A.a: " << A.a << endl;
      }
    
      void funct2(MyClass<T> &B) {
        B.a +=  2;
        cout << "A.a: " << B.a << endl;
      }
    
    };
    
    int main() {
      MyClass<int> myclass(0);
      MyFriend<int> myfriend;
    
      myfriend.funct1(myclass);
      myfriend.funct2(myclass);
    
      return 0;
    }