什么是重载"<<"时的"std::ostream&(*f)(std::ostream &)",为什么我需要它?
What is `std::ostream& (*f)(std::ostream &)` when overloading `<<` and why I would need it?
我正在包装器中工作boost.log
并发现这个问题似乎是我想要的,但不是std::cout
而是与我还不知道的boost
流有关的东西。为此,我一直想知道为什么需要它以及它实际上在做什么。例如:
MyCout& operator<< (MyCout &s, std::ostream& (*f)(std::ios &)) {
f(std::cout);
return s;
}
在这种情况下,我理解(或者可能不理解?)我正在使用std::ostream& (*f)(std::ios &)
重载运算符<<
以进行MyCout
,但这是为什么呢?f(std::cout)
实际上做了什么,为什么我需要用这个函数重载运算符?似乎根本没有使用s
,只是通过操作员并返回与以前相同的内容。
谢谢!
std::ostream& (*f)(std::ios &)
是一个名为 f
的函数指针,它指向将std::ios &
作为其唯一参数并返回std::ostream&
的函数。 对于某些流操纵器(如 std::endl
)是必需的,这是一个函数,而不是像std::cout
那样的对象。
使用此重载,您可以将函数流式传输到流中,并让该函数对流进行某种操作
不要说这个函数签名不是你真正想要的。 输入参数类型和返回类型应相同。 采用机械手功能的operator <<
的标准重载为
basic_ostream& operator<<(
std::ios_base& (*func)(std::ios_base&) );
basic_ostream& operator<<(
std::basic_ios<CharT,Traits>& (*func)(std::basic_ios<CharT,Traits>&) );
basic_ostream& operator<<(
std::basic_ostream<CharT,Traits>& (*func)(std::basic_ostream<CharT,Traits>&) );
basic_istream& operator>>(
std::ios_base& (*func)(std::ios_base&) );
basic_istream& operator>>(
std::basic_ios<CharT,Traits>& (*func)(std::basic_ios<CharT,Traits>&) );
basic_istream& operator>>(
basic_istream& (*func)(basic_istream&) );
相关文章:
- boost::interprocess::file_lock 与 std::ostream 一起使用时的错误行为
- 与'operator<<'不匹配(操作数类型'std::ostream {aka std::basic_ostream<char>}'
- 与"operator<<"不匹配(操作数类型'std::ostream'
- 运算符的歧义错误<<自定义 std::ostream 子类中的重载
- 关于 std::ostream 构造函数
- STD :: Ostream忽略了通过setf()在基础上设置的十六进制标志
- 将 std::ostream 转换为 std::string
- STD :: Ostream:类是不可接受的[C ]
- 为什么在三元运算符中使用STD :: Ostream不会编译
- 当我编译引用 std::ostream 时,我有一个奇怪的错误弹出
- 如何跟踪写入std :: Ostream对象的字节数
- std::ostream的下降表达(针对SFINAE)
- BOOST ::变体无法解决运算符&lt;&lt;对于STD :: Ostream
- 我什么时候应该返回 std::ostream
- 如何移动std::ostream
- 如何在自定义 std::ostream 类中使用 std::endl
- 如何清除std::ostream
- 返回对此的引用时出现意外的std::ostream输出
- std::ostream to QDataStream
- 使用 std::ostream 方法将格式化文本输出到 std::string 对象