如何正确实现C++流操纵器endl

How to implement C++ stream manipulator endl correctly?

本文关键字:操纵 endl C++ 何正确 实现      更新时间:2023-10-16

我正在尝试为stream类实现一个操纵器。我对操纵者不太了解,但我认为我做的每件事都是对的。代码的相关部分如下:

class stream
{
public:
stream& operator<<(bool b) { // send bool value and return *this; }
stream& operator<<(const char str[]) { // send string and return *this }
}; 
inline stream& endl(stream& s) 
{
return s << "rn";
}

class stream stream;
int main()
{
stream << endl;
}

我不知道我做错了什么,但编译器不是调用endl,而是调用stream::operator<<(bool)。知道吗?

看到stream << endl;,编译器必须从您提供的operator <<中选择一个重载。endl不能转换为const char *,但它可以转换为bool,所以这就是您得到的。

你可能想添加一个过载

stream& operator<<(stream &(*function)(stream &)) {
return function(*this);
}

CCD_ 9内部正确处理函数指针。

由于endl既不是bool也不是const char[](它是一个自由函数),因此它被隐式转换为bool(true),并调用以下函数:

stream::stream& operator<<(bool b)

您可以将endl定义为特殊类型的endl_t,并为其定义正确的运算符:

#include <iostream>
#include <string>
#include <array>
//Just make the operators `explicit`. See [this excellent answer on SO](http://stackoverflow.com/a/8239402/5470596).
class stream
{
public:
stream& operator<<(bool b) { std::cout << "booln" ; return *this; }
stream& operator<<(const char str[]) { std::cout << "const char[]n" ; return *this; }
};
struct endl_t {} endl;
stream& operator<<(stream& s, endl_t)
{
s << "rn";
return s;
}

int main()
{
stream s;
s << endl; // prints "const char[]"
}

在coliru 上直播