1

I found this beautiful little helper on this site: Howto throw std::exceptions with variable messages?

class Formatter
{
public:
  Formatter() {}
  ~Formatter() {}

  template <typename Type>
  Formatter & operator << (const Type & value)
  {
      stream_ << value;
      return *this;
  }

  std::string str() const         { return stream_.str(); }
  operator std::string () const   { return stream_.str(); }

  enum ConvertToString 
  {
      to_str
  };
  std::string operator >> (ConvertToString) { return stream_.str(); }

private:
  std::stringstream stream_;

  Formatter(const Formatter &);
  Formatter & operator = (Formatter &);
};

It can be used like

    std::string foo(Formatter() << "foo" << 42);

To allow enabling/disabling of the stream input I extended the class with

bool enabled;

enum class status {
  active, inactive
};

Formatter& operator << (status s)
{
  if (s == status::active) enabled = true;
  if (s == status::inactive) enabled = false;
  return *this;
}

and changed the input template to if (enabled) stream_ << value;

Now I can do

std::string optional = "";
std::string foo(Formatter()
  << "foo"
  << (optional.empty() ? Formatter::status::inactive : Formatter::status::active)
  << "bar" << optional
  << Formatter::status::active
  << "!");

Now I´m looking for a way to get rid of status and use Formatter::inactive directly instead.

Community
  • 1
  • 1
downforme
  • 371
  • 2
  • 15

0 Answers0