Template class and insert extraction are overloaded

How can I make the insert (<<) and / or extract (β†’) operator overload in the template class WITHOUT making it inline. I would like to have a <or β†’ operator as a friend class. I know how to make it inline inline example in matrix class

friend ostream& operator<<(ostream& ostr, const Matrix<T>& inputMatrix) { ... // create the ostr return ostr; } 

but I would like to have code outside the template definition.

g ++ told me to add <> after the function name so that I would do it, but when I tried to initialize a matrix of type SOMETYPE, it gave me an error that it did not know how to extract or insert for this type.

+4
source share
3 answers

If you really want to define an operator from the outside and make friends only with an instance of the operator that matches the type with that instance of the template, the correct syntax is:

 template <typename T> class test; // forward declare template class template <typename T> // forward declare the templated operator std::ostream& operator<<( std::ostream&, test<T> const & ); template <typename T> class test { // define the template friend std::ostream& operator<< <T>( std::ostream&, test<T> const & ); // befriend }; template <typename T> // define the operator std::ostream& operator<<( std::ostream& o, test<T> const & ) { return o; } 

In most cases, you should not pull the definition from the class, given that you still need to provide it in the header and additional work.

Also note that there are slight differences for the compiler regarding search. In the case when the function is built into the class definition, the compiler will not find this function unless one of the arguments is of the type of the template, therefore, it effectively reduces the visibility and the amount of work that the compiler should do, do (if the templated operator<< is defined outside class, the compiler will find it as a candidate for overload resolution in all places where it finds a << b , only to drop it in all cases when the second argument is not test<T> (and it will show the template operator as a candidate in all messages about mistake x, where it cannot match operator<< , which is already a long enough list).

+1
source

Try something like:

 template <typename T> class Matrix; template <typename T> std::ostream& operator<<(std::ostream& ostr, const Matrix<T>& m); template <Typename T> class Matrix { public: friend ostream& operator<< <T> (ostream& ostr, const Matrix<K>& inputMatrix); }; // This must be in the same translation unit as the class definition! template<typename T> ostream& operator<<(ostream& ostr, const Matrix<T>& inputMatrix) { // ... return ostr; } 

Link Block Link

re-edited to view comments made by asepler and dribeas.

+2
source

Put the code in the header, outside the class definition. Or, put it in a .tcc file and include it at the bottom of the header.

+1
source

All Articles