Jak przeciążyć operator strumienia w klasie szablonowej

AklimX

     1 Pierwszy przykład
     2 Drugi przykład
     3 Komentarz

Pierwszy przykład

źródło: http://4programmers.net/Forum/312426#id312426

#include <iostream>
using namespace std;

    // deklaracja szablonu klasy
template <class Tp> class C; 
    // deklaracja szablonu operatora <<
template <class Tp> ostream& operator<< (ostream &, const C<Tp> &); 

    // deklaracja klasy
template <class Tp>
class C
{
public:
   Tp war;
   friend ostream& operator<< <> (ostream &, const C<Tp> &); // Uwazaj na te nawiasy <>  !!
};

template <class Tp> ostream& operator<< (ostream &os, const C<Tp> &c) // tutaj juz tych nawiasow nie ma! Nie ma też słówka friend
{
   os << c.war;
   return os;
}
int main()
{
   C<int> zmienna;
   zmienna.war = 5;
   cout << zmienna;
}

Drugi przykład

źródło: http://4programmers.net/Forum/312441#id312441

#include <iostream>
#include <sstream>
#include <cstring>

using namespace std;

    // konieczne deklaracja szablonów!
template <class T, int size> class IntArray;
template <class T, int size> ostream& operator<< (ostream& os, const IntArray<T, size>& ia);
template <class T, int size> istream& operator>> (istream& is, IntArray<T, size>& ia);

    // deklaracja klasy
template <class T, int size>
class IntArray
{
      T i[size];
public:
       IntArray() { memset(i, 0, size * sizeof(T));}
       T& operator[](int x) { return i[x]; }
       
       friend ostream& operator<< <>(ostream& os, const IntArray<T, size>& ia);
       friend istream& operator>> <>(istream& is, IntArray<T, size>& ia);
};


template <class T, int size>
ostream& operator<<(ostream& os, const IntArray<T, size>& ia)
{
   T i(0);
   for(int j = 0; j < size; j++)
   {
      os << ia.i[j];
      if ( j != size - 1)
      os << ",";
   }
   os << endl;
   return os;
}

template <class T, int size>
istream& operator>>(istream& is, IntArray<T, size>& ia)
{
   for(int j = 0; j < size; j++) is >> ia.i[j];
   return is;
}

int main()
{
    stringstream input("47 34 56 92 103");
    IntArray<int, 5> I;
    input >> I;
    I[4] = -1;
    cout << I;
    system("pause");
}

Komentarz

w/w kody działają bez problemu w Code::Blocks (GCC, MinGW) oraz BCB 6, natomiast w VC++ 6 potrzebna jest drobna zmiana (usunięcie ostrych nawiasów)

    friend ostream& operator<< <> (ostream &, const C<Tp> &);

na

    friend ostream& operator<< (ostream &, const C<Tp> &);
FAQ

4 komentarzy

w Dev-C++ jak i w VC++2005 dziala tez wersja (i w devie tylko ta dziala):

template <class T> friend ostream& operator<< (ostream &, const C<T> &);

z tym ze parametr w klasie musi byc inny niz parametr w funkcji (chodzi o <class T>)

Bardzo dobrze, że to tutaj dodałeś, bo z tymi funkcjami zaprzyjaźnionymi to zamota jest przy szablonach :)

P.S. W VC++ 8.0 (2005) już się nie pluje o "<>"

:) niom, dla Ciebie nawet bardzo

Wyglada tak jakby znajomo :)