Error : friend function not declared in this scope

Viewed 103

/****************pair.h******************/

 #include<iostream>
    using namespace std;
    template<class T1,class T2>
    class Pair
    {
    private :
      T1 first;
      T2 second;
    public  :
      Pair(T1,T2);
      Pair(){};
      Pair<T1,T2>  make(T1  a , T2  b);
      void operator=(const Pair& other);
      friend ostream& operator<<(ostream& out ,const Pair<T1,T2>& A);

    };

/*******************main.cpp*********************/

#include<iostream>
#include<utility>
#include"Pair.h"
using namespace std;

int main()
 {
  Pair<int,int> A=make(10,20);
 cout << A ;
  return 0;
}

/***********************pair.cpp******************/

#include"Pair.h"
 #include<ostream>
 using namespace std;

template<class T1, class T2>
 Pair<T1,T2>::Pair(T1 a,T2 b){
   this->first = a;
   this->second = b;
 }

 template<class T1, class T2>
void  Pair<T1,T2>::operator=(const Pair& other)
 {
    this->first = other.first;
    this->second = other.second;
 }

 template<class T1, class T2>
ostream& operator<<(ostream& out ,const Pair<T1,T2> A)
{
  out<<"("<<A.first<<" , "<<A.second<<")";
  return out;
}

 template<class T1, class T2>
 Pair<T1,T2> make(T1   a , T2   b)
{
  return (Pair<T1,T2> (a,b)) ;
    }

it gives me an error in function make ; as it was not declared in the scope of main and i don't understand why. Also there is a problem when it comes to all friend functions and template. The program doesn't want to be compiled.

2 Answers

make is a global function. Your header file should look like this

template<class T1,class T2>
class Pair
{
private :
  T1 first;
  T2 second;
public  :
  Pair(T1,T2);
  Pair(){};
  void operator=(const Pair& other);
  friend ostream& operator<<(ostream& out ,const Pair<T1,T2>& A);

};

template<class T1,class T2>
Pair<T1,T2>  make(T1  a , T2  b);

Plus you have other problems with your code. For one all your code should be in the header file, as is explained in the linked question in the comments above.

See also this question for the template friend issue

Overloading friend operator << for template class

make is function of class Pair so, Use it with a object of class Pair like:

#include<iostream>
#include<utility>
#include"Pair.h"
using namespace std;

int main()
{ Pair pObj;
  Pair<int,int> A= pObj.make(10,20);
  cout << A ;
  return 0;
}
Related