can I specialize operator<<?
I want to specialize operator<< but this code is not compiling;
template<>
std::ostream& operat开发者_如何学编程or<< < my_type >( std::ostream& strm, my_type obj);
To specialize a template, first you have to have a template declared.
In the case of a free operator<<
you don't need a template; you can just overload it for your my_type
class:
std::ostream& operator<<( std::ostream& strm, my_type obj );
If your object isn't trivial in size, you may want to consider passing via a const reference so that you don't copy it every time you stream it:
std::ostream& operator<<( std::ostream& strm, const my_type& obj );
(Technically you can explicitly specialize an operator<<
, but I don't think that this is what you want or need. In order to be able to use a template operator<< with the usual << syntax you need to make the template specialization deducible from one of the parameter types.
E.g.
// template op <<
template< class T >
std::ostream& operator<<( std::ostream&, const MyTemplClass<T>& );
// specialization of above
template<>
std::ostream& operator<< <int>( std::ostream&, const MyTemplClass<int>& );
)
Why not just overload?
// no template <>
std::ostream& operator<<( std::ostream& strm, my_type obj);
You only specialize when there exists a template to specialize.
Your parameter should probably be const my_type&
, to avoid a needless copy.
精彩评论