c++ - 我可以专门化运算符<<吗?

标签 c++ templates operator-overloading

我想专门化运算符<<,但此代码无法编译;

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/

相关文章:

Ruby 重载 + 运算符

C++ Vector Find() 重载运算符 - 错误

c++ - 运行 SFML 图形后看不到新窗口

c++ - 类里面的 setter和getter

c++ - 尝试使用共享库部署 Qt 应用程序时出错

c++ - 实例化一个模板类,该模板类在具有不同函数签名的构造函数中采用函数指针

c++ - 推导使用循环模板的函数的参数

c++ - 使用 QMediaPlayer 播放资源中的 mp3 文件

templates - 是否可以创建新的工作表并将文件中的数据添加到其中?

c++ - 在 C++ 中,如何在指向对象的指针上调用偏移运算符