Question

```

#include <iostream>
#include <sstream>
#include <QString>
class Printer {
public:
    inline std::ostream& operator<<(const std::string& str) {
    stream << str;
    return stream;
    }
    inline std::ostream& operator<<(int numb) {
    stream << numb;
    return stream;
    }
    inline std::ostream& operator<<(const QString& str) {
    stream << str.toStdString();
    return stream;
    }
    virtual ~Printer(void) {
    std::cout << stream.str();
    }

private:
    std::stringstream stream;
};

int main(void)
{
    QString qstring("qstring");
    std::string stdstring("std::string");

    Printer() << qstring << stdstring << 1;   // Works like charm
    Printer() << stdstring << qstring << 1;   // Doesnt work :(

    return 0;
}

```

Can anyone please have a look at the code above and tell me whats the issue in main method where i have comments

Était-ce utile?

La solution

For your original code

Printer() << stdstring << qstring

equals to

(Printer().operator<<(stdstring)).operator<<(qstring)

You can see the problem here,

Printer() << stdstring

will return a ostream &, and you pass QString to ostream. I think you should return Printer other than the stream.

class Printer {
public:

    virtual ~Printer(void) {
        std::cout << o.str();
    }

    std::stringstream o;
};

Printer &operator<<(Printer &p, const std::string &s)
{
    p.o << s;
    return p;
}

Printer &operator<<(Printer &p, const QString &s)
{
    p.o << s.toStdString();
    return p;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString qstring("qstring");
    std::string stdstring("std::string");
    Printer p;

    p << stdstring << qstring;

    return a.exec();
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top