2

/****************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.

sharlotte
  • 43
  • 5
  • 1
    Does this answer your question? [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Richard Critten May 07 '20 at 20:41
  • The OP is asking about compilation errors. So the header file issue is not the only thing wrong with this code, and not what the OP is asking about. I'm voting to reopen. – john May 07 '20 at 20:49

2 Answers2

0

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

john
  • 85,011
  • 4
  • 57
  • 81
0

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;
}
user9559196
  • 157
  • 6