Templates

I have a few questions about templates.

1.If I declare operator<< as a friend in a generic class,how can I define it outside class?What should I write?
i.e. template < typename T >
class K {
friend ostream& operator<< (ostream& it, const Podatak&);
};
How to define operator<< now?

2.Is it possible to derive other classes from generic classes and how?If yes can generic classes be abstract?

I appreciate any help,thx...
1) Since the function in your example seems to be totally unrelated to K, you'd create it just as if 'K' wasn't a template at all:

1
2
3
4
5
6
7
8
9
10
template < typename T >
class K {
friend ostream& operator<< (ostream& it, const Podatak&);
};

ostream& operator << (ostream& it,const Podatak& p)
{
  // this function is a friend of K<T>
  // but what is the point of that?  It isn't related to K<T>
}


A more sensible friend function for this K template would might look like so:

1
2
3
4
5
6
7
8
9
10
11
12
template <typename T>
class K {
friend ostream& operator<< (ostream& it, const K<T>& ); // note a K<T> object on the right
};

// then define it:

template <typename T>
ostream& operator << (ostream& it,const K<T>& k)
{
 // friend of K<T>
}



2) Provided you have a type. Keep in mind that K is not a class, it's a template. So you can't derive from K. You can, however, derived from K<T>:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template <typename T>
class K { };

// derive from K<int>:
class Foo : public K<int>
{};

// a template child:
template <typename T>
class Bar : public K<T>
{};

/*
  Foo derives from K<int>
  Bar<int> derives from K<int>
  Bar<float> derives from K<float>
  etc
*/


And yes, K<T> can be abstract.
Last edited on
Topic archived. No new replies allowed.