Declaring a class function as a friend of a template class

#include< iostream>  
using namespace std;  

template< class t>  
class X  
{  
  private:  
      t x;    

  public:  
        template< class u>  
         friend u y::getx(X< u> ); 

      void setx(t s)  
      {x=s;}  
           };      

class y   
{  
 public:  
     template< class t>  
     t getx(X< t> d)  
     {return d.x;}     
};  

int main()  
{  
    X< int> x1;  
    x1.setx(7);  
    y y1;  
    cout<< y1.getx(x1);    
    return 0;  
}       

When compiling the above program, an error was detected that yis neither a function nor a member function, therefore it cannot be declared a friend. How to include getxas a friend in X?

+3
source share
2 answers

You must forward the y class before the XIe class template, just put:

class y; // forward declaration

template class X ...

+1
source

You need to arrange the classes so that the function declared as a friend is actually visible before the class X. You also need to make X visible before y ...

template< class t>  
class X;

class y   
{  
 public:  
     template< class t>  
     t getx(X< t> d)  
     {return d.x;}     
};

template< class t>  
class X  
{  
  private:  
      t x;    

  public:  
        template< class u>  
         friend u y::getx(X< u> ); 

      void setx(t s)  
      {x=s;}  
};      
+2
source

All Articles