我想专门化运算符<<,但此代码无法编译;
template<>
std::ostream& operator<< < my_type >( std::ostream& strm, my_type obj);
最佳答案
要专门化模板,首先必须声明一个模板。
在免费的情况下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>& );
)
关于c++ - 我可以专门化运算符<<吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3285019/