Reputation: 8277
Let's say a define a custom type in my c++ code to handle vectors in 3d:
typedef tuple<double,double,double> vector3d;
Is it possible to add a method to that so that I can quickly output their coordinates using:
vector3d somevector(1,1,1);
cout << somevector << "\n";
I know I could do it wrapping these objects in a class
or a struct
but is it possible to do it more straightforwardly?
Upvotes: 0
Views: 37
Reputation: 5279
Overload streaming operator for ostream
.
typedef tuple<double,double,double> vector3d;
ostream& operator<<(ostream& os, const vector3d& vec)
{
os << '(' <<
std::get<0>(vec) << ',' <<
std::get<1>(vec) << ',' <<
std::get<2>(vec) << ')';
return os;
}
int main(int argc, char *argv[])
{
cout << vector3d(1, 2, 3);
return 0;
}
Upvotes: 2