My question is different because it is pertaining to a newer version of C++.
This question was asked already here and I'm referring to this answer. However this was asked and answered back in 2009 and it is quite dated to the current compilers and versions of the C++ language. However; here it is again.
I have a simple template class that I would like to overload the stream operator, but in my case here: I'm using Visual Studio 2017 CE v4.6.01055 with compiler c++ language feature set to ISO C++ Latest Draft Standard (/std:c++latest)
simply put C++17. I'm build it in x86 debug mode.
I have tried the solution from the Q/A above but it keeps giving me compiler errors.
Here is the simple class
template<class T>
class Point {
public:
T mX;
T mY;
Point() : mX(0), mY(0) {}
Point( T x, T y ) : mX( x ), mY( y ) {}
Point( T& x, T& y ) : mX( x ), mY( y ) {}
Point( T* x, T* y ) : mX( *x ), mY( *y ) {}
friend operator<<( std::ostream& out, const Point<T>& p );
}
The suggestion stated that you should make a single instance called specialization
of that template a friend. The user also stated that you needed to put the declaration of operator<<
above the class template declaration. I've tried that; I've tried moving the method out the header into the cpp, below, above it; I tried to even put the definition within the class as well, and no matter what I try; I can not get it to compile correctly.
I even found this answer and I tried the pattern there but it is still failing in c++17. At least at this point it is compiling
without the <>
specialization and failing to build, but when I add that in it fails to compile.
What is the proper syntax and or placement to overload the stream operator as a friend to a simple class template in c++17? I don't necessarily mean the syntax of the actual operator<<()
itself... it had to deal more with the actual placement of the declarations and definitions. The only piece of syntax that I wasn't sure of but found out from the previous answers that I've shown here was the part about making it a specialization; that part was new to me.
EDIT
I don't know what was causing the compiler or linker errors. The declarations and definitions were the same. I ended up changing the 2nd param from const Point<T>&
to Point<T>
in the declarations and definition and it compiled and built. I then went ahead and changed them back to const Point<T>&
and it now compiles, builds and gives me the output without error.
It could of been a bug within Visual Studio since I did just update it to the newest version last night. I don't know what was causing it; but what ever it was is now resolved.