<< Overloading for STL containers

Hello, I'm struggling with templates right now, and have managed to overeload the << operator to print STL containers:

1
2
3
4
5
6
7
8
template <template <class,class> class cont_type, class T>
ostream& operator<<(ostream& os, const cont_type <T,allocator<T>>& cont){
	for(const auto& i : cont){
		os<<i<<" ";
	}
	os<<endl;
	return os;
}


This code works successfully for printing STL vectors,lists,deques(and maybe other?).


However, I feel like I could improve something regarding the default allocator<T> parameter. If I'm trying to print(cout<<) a vector which hasn't been constructed with the default allocator type(allocator<T>) the code wouldn't work I guess. Could I replace the first two lines of code with something like this ?


1
2
template <template <class,class =allocator<T>> class cont_type, class T>
ostream& operator<<(ostream& os, const cont_type <T>& cont)


Last edited on
Close, but you are putting it in the wrong spot.
Name it, and use it in-place:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <memory>

template <template <class, class> class Container, class T, class Alloc = std::allocator <T> >
std::ostream& operator << ( 
  std::ostream& os,
  const Container <T, Alloc> & container )
{
  const char* sep[] = { "", ", " };
  int si = 0;
  os << "{ ";
  for (const T& elt : container)
  {
    os << sep[si] << elt;
    si = 1;
  }
  return os << " }";
}

#include <vector>
using namespace std;
int main()
{
  vector <int> xs{ 2, 3, 5, 7, 11, 13 };
  cout << xs << "\n";
}

Hope this helps.
Your code does indeed work. However, the compiler deduces that the third template parameter of my overload is the allocator I used to construct the container, from what I see.
My english is bad and I fell like I'm unable to express my thoughts clearly.

The template parameter Alloc is not used with its default value. To demonstrate, this compiles with no issue:

1
2
3
4
5
template <template <class,class> class cont_type, class T,class Alloc=alligator<T>>
//.....
list<int>a(5,-1);
list<int,allocator<char>> b(5,0);
cout<<a<<b;


Therefore, the default argument could be left out. Right ?
Because this compiles the same:

1
2
3
4
5
template <template <class,class> class cont_type, class T,class Alloc>
//.....
list<int>a(5,-1);
list<int,allocator<char>> b(5,0);
cout<<a<<b;


Please correct me if I'm wrong.
Topic archived. No new replies allowed.