0

I'm trying to create a logger function where you can pass in a message which will be logged to a text file. Sometimes I'd like to pass in a variable concatenated with my message so I could do something like:

logger("The variable is: " + variable);

The function is defined as

void logger(std::string message);

I'm using Qt, so I don't know if it's relevant but the variable will always be a QString. When I tried this it would say that no candidate function for

void logger(const QString);

So I thought why not make a second function where it would expect a concatenation:

void logger(std::string message);
void logger2(const QString message);

It compiled fine when I did

logger2("The variable is: " + variable);

However, when I debugged the passed message variable was an empty string. How do I get this to work, is it possible?

2
  • 1
    Do you mean const QString&? Commented Mar 22, 2011 at 19:39
  • variable is almost always a QString. I would have done const QString& but the error message said I was doing const QString. Having const QString& doesn't work as "Text" + QString == const QString. If I do const QString& it doesn't compile Commented Mar 22, 2011 at 19:42

2 Answers 2

6

Why not just do something like this:

QString qs = "hello";
qs.toStdString();

As far as concatenating on the fly, I like to use a simple formatter class:

class Formatter
{
public:
    template<class Val> Formatter& operator<<(const Val& val)
    {
        ss_ << val;
        return * this;
    }
    operator string () const { return ss_.str().c_str(); }
private:
    std::stringstream ss_;
};

...which can be used like this:

logger(Formatter() << "The variable is: " << variable);
Sign up to request clarification or add additional context in comments.

1 Comment

BTW, you can see a code review of my Formatter class here: codereview.stackexchange.com/questions/226/…
0

have you tried logger("The variable is: " + variable.toStdString()); ?

1 Comment

Sorry for the late comment. The QString include should do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.