如何正确实现C++流操纵器endl
How to implement C++ stream manipulator endl correctly?
我正在尝试为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 上直播
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- C++setiosflags函数操纵器-未确定的缩进
- C++表达SFINAE和ostream操纵器
- 操纵安卓相机的深度图导致应用程序崩溃
- 什么是现实中的"endl"(或任何输出操纵器)?它是如何实现的,它如何与操作员<<一起工
- std::endl,在 Python 中是否有等价物?(返回 + 刷新)
- 运算符 << 操作加载的 API for std::endl?
- 我在 C++ 中创建了一个函数来递归反转字符串,但是之后如何使功能打印一个 endl?
- 可变参数模板函数:调用没有匹配函数,std::endl
- 有关具有编译错误的操纵列表的问题
- C++自定义流操纵器,用于更改流上的下一个字符串
- 如何使用自定义流操纵器在类实例中保存数据
- 如何键入用于const对象的自定义io操纵器
- 如何实现接受参数的自定义流操纵器?
- 模板推导不适用于 std::endl?
- std::cout << glGetString(GL_RENDER) << std::endl;抛出错误但不GL_Renderer或GL_Verision,我不知道为什么?
- std::flush 不起作用,而 std::endl 可以
- "cout<<count<<endl;"没有打印任何内容
- 如何正确实现C++流操纵器endl
- 如何为我的类创建endl操纵器