views:

75

answers:

2

Hi,

I want to specialize operator<< but this code is not compiling;

template<>

std::ostream& operator<< < my_type >( std::ostream& strm, my_type obj);
+1  A: 

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.

GMan
Yes I know about overloading, I need to overload operator<< for a group of types, imagine that inside of operator body I'm checking types for some T1, T2 or t3, doing one thing for them and another for all other types
Davit Siradeghyan
@Davit: How about instead of 'imagine', you post the bigger picture in he question? :) The more information we get, the better the answer. (In other words: post the problem, not the step.)
GMan
This is my codetemplate< typename T >std::ostreamand I want to specialize operator<< for some T1, T2 and T3 types which are not POD types.
Davit Siradeghyan
+1  A: 

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>& );

)

Charles Bailey
Charles please read my comment which I wrote for GMan's answer
Davit Siradeghyan
@Davit Siradeghyan: If you have a template which is a catch all for *all* types (needless to say this is almost always a bad idea), then you can specialize it but it is still simpler to overload it for your particular types. Overload resolution will chose an exact match of a non-template function over a function template.
Charles Bailey
I'm with Charles, having a totally generic insertion operator seems really dangerous.
GMan