1

我正在尝试为我的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 << "\r\n";
}


class stream stream;

int main()
{
    stream << endl;
}

我不知道我做错了什么,但不是调用endl编译器而是调用stream::operator<<(bool). 任何的想法?

4

2 回答 2

5

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

您可能打算添加一个重载

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

其中class stream正确处理函数指针。

于 2017-02-09T17:50:19.693 回答
1

由于 yourendl既不是 abool也不是 a const char[](它是一个自由函数),它被隐式转换为 a 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 << "bool\n" ; 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 << "\r\n";
    return s;
}


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

以大肠杆菌为生

于 2017-02-09T17:54:21.803 回答