【发布时间】:2010-07-19 20:56:03
【问题描述】:
我想专门化操作符
template<>
std::ostream& operator<< < my_type >( std::ostream& strm, my_type obj);
【问题讨论】:
标签: c++ templates operator-overloading
我想专门化操作符
template<>
std::ostream& operator<< < my_type >( std::ostream& strm, my_type obj);
【问题讨论】:
标签: c++ templates operator-overloading
要专门化一个模板,首先你必须声明一个模板。
如果是免费的operator<<,则不需要模板;你可以为你的my_type 类重载它:
std::ostream& operator<<( std::ostream& strm, my_type obj );
如果您的对象大小不一,您可能需要考虑通过 const 引用传递,这样您就不会在每次流式传输时都复制它:
std::ostream& operator<<( std::ostream& strm, const my_type& obj );
(从技术上讲,您可以明确专门化 operator<<,但我认为这不是您想要或需要的。为了能够使用具有通常
例如
// 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>& );
)
【讨论】:
为什么不只是过载?
// no template <>
std::ostream& operator<<( std::ostream& strm, my_type obj);
只有在存在模板时才能进行专业化进行专业化。
您的参数可能应该是const my_type&,以避免不必要的复制。
【讨论】: