I'm trying to get up to speed on "modern" C++ particularly using templates. I've got a class Point that overrides the << operator. Works fine. So then I decided to add nice print out for containers in general.
My question - is there a way write a template for multiple container types similar to the code below?
template <typename T>
std::ostream& operator <<(ostream& os, const vector<T>& v)
{
os << "\n";
for( auto x : v ) { os << "\n\t" << x; }
os << "\n";
return os;
}
The code above correctly outputs vectors in a multi-line format as long as T has an << operator. I'd like to make this work for other containers like lists etc.
I also realize that it's probably a bad idea (or at least rude) to override output for containers in a general way for all types. So ultimately the template code above would have the typename hard coded/restricted to 'Point' and a template-ed container.
OK, implimenting AndyG's suggestion I have the following full code:
#include <iostream>
#include <map>
#include <vector>
using namespace std;
struct Point {
double x, y, z;
Point() : x(0), y(0), z(0) {};
Point(double a, double b, double c) : x(a), y(b), z(c) {}
Point(double a[]) : x(a[0]), y(a[0]), z(a[0]) {}
friend std::ostream& operator <<(ostream& os, const Point&p)
{
os << p.x << ", " << p.y << ", "<< p.z;
return os;
}
};
template <template<class> class C, class... T>
std::ostream& operator <<(ostream& os, const C<T...>& v)
{
os << "\n";
for( auto x : v ) { os << "\n\t" << x; }
os << "\n";
return os;
}
vector<Point> vp = { { 1, 2, 3 },
{ 5, 7, 4 },
{ 8, 2, 5 }
};
int main(int argc, char* argv[])
{
cout << vp[0]; // works
cout << vp; // dosen't work,
}
But still no luck. The compiler can't match operator<< with 'std::vector'
I had tried many variations of the template <template>
prior to my first post with about the same results. I can get a template that compiles but the compiler fails to match the operator function and use the template.
I wasn't aware of the variadic template pack, obviously a good idea but doesn't solve the problem.