1
\$\begingroup\$

This class allows me to quote strings being sent to an output stream:

class Quote{
public:
    friend std::ostream& operator<<(std::ostream& os, const Quote& obj){
        obj.write(os);
      return os;
    }
    Quote() = delete;
    Quote(const string & text): text(text){}

    void write(ostream & os) const{
        os << default_quote_token << text << default_quote_token;
    }
private:
    const string & text;
};

Like this:

os << Quote(name);

It feels like a lot of work to avoid:

os << "\"" << name << "\"";

Is there a better solution?

\$\endgroup\$
1
  • \$\begingroup\$ Apart from minor formatting issues I see nothing wrong. You could extend to support other types (and/or multiple objects). \$\endgroup\$ Commented Oct 2, 2015 at 6:23

1 Answer 1

2
\$\begingroup\$

In C++14, there's std::quoted. Some advantages it has over your approach:

  • It works with both output and input streams

  • You can specify the delimiter and escape character

  • It's a stream manipulator, allowing it to be used seamlessly with operations while yours is a one-off class with zero interoperability

  • It supports wide strings

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.