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(constauto& 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)
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;