类模板的友元声明

时间:2021-05-31 20:02:36

   在一个模板可以被用在一个类模板的友元声明中之前它的声明或定义必须先被给出

#include <iostream>
#include <cstddef>       // for size_t
using namespace std;
class alloc {
};
template <class T, class Alloc = alloc, size_t BufSiz = 0>
class deque {
public:
  deque() { cout << "deque" << ' '; }
};

template <class T, class Sequence>
class stack;
template <class T, class Sequence>
bool operator==(const stack<T, Sequence>& x,
                   const stack<T, Sequence>& y);
template <class T, class Sequence>
bool operator<(const stack<T, Sequence>& x,
                  const stack<T, Sequence>& y);

template <class T, class Sequence = deque<T> >
class stack {
  //  寫成這樣是可以的
 friend bool operator==  <T>  (const stack <T> &, const stack<T> &);
friend bool operator<   <T>  (const stack <T> &, const stack<T> &);
  //  寫成這樣也是可以的
 /* friend bool operator==  <T>  (const stack&, const stack&);
  friend bool operator<   <T>  (const stack&, const stack&);*/
  //  寫成這樣也是可以的
 //friend bool operator==  <> (const stack&, const stack&);
 //friend bool operator<   <> (const stack&, const stack&);
  //  寫成這樣就不可以
 //friend bool operator== (const stack&, const stack&);
// friend bool operator<  (const stack&, const stack&);
public:
  stack() { cout << "stack" << endl; }
private:
  Sequence c;
};
template <class T, class Sequence>
bool operator==(const stack<T, Sequence>& x,
                   const stack<T, Sequence>& y) {
  return cout << "operator==" << '\t';
}
template <class T, class Sequence>
bool operator<(const stack<T, Sequence>& x,
                  const stack<T, Sequence>& y) {
  return cout << "operator<" << '\t';
}
int main()
{
  stack<int> x;               // deque stack
  stack<int> y;               // deque stack
  cout << (x == y) << endl;   // operator==   1
  cout << (x < y) << endl;    // operator<    1
  stack<char> y1;             // deque stack
  return 0;
}