The Battle for Wesnoth  1.15.1+dev
formatter.hpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
3  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13 */
14 
15 #pragma once
16 
17 #include <sstream>
18 #include <utility>
19 
20 /**
21  * std::ostringstream wrapper.
22  *
23  * ostringstream's operator<< doesn't return a ostringstream&. It returns an
24  * ostream& instead. This is unfortunate, because it means that you can't do
25  * something like this: (ostringstream() << n).str() to convert an integer to a
26  * string, all in one line instead you have to use this far more tedious
27  * approach:
28  * ostringstream s;
29  * s << n;
30  * s.str();
31  * This class corrects this shortcoming, allowing something like this:
32  * string result = (formatter() << "blah " << n << x << " blah").str();
33  *
34  * Actually, due to the ref qualified versions below, you can get away with this
35  *
36  * string result = formatter() << "blah " << n << x << " blah";
37  */
38 class formatter
39 {
40 public:
42  stream_()
43  {
44  }
45 
46  template<typename T>
47  formatter& operator<<(const T & o)
48 #if HAVE_REF_QUALIFIERS
49  &
50 #endif
51  {
52  stream_ << o;
53  return *this;
54  }
55 
56 #if HAVE_REF_QUALIFIERS
57  template <typename T>
58  formatter && operator<<(const T & o) && {
59  stream_ << o;
60  return std::move(*this);
61  }
62 #endif
63 
64  std::string str() const {
65  return stream_.str();
66  }
67 
68  // Implicit x-value conversion to string
69  operator std::string() const
70 #if HAVE_REF_QUALIFIERS
71  &&
72 #endif
73  {
74  return stream_.str();
75  }
76 
77 private:
78  std::ostringstream stream_;
79 };
formatter & operator<<(const T &o)
Definition: formatter.hpp:47
std::ostringstream wrapper.
Definition: formatter.hpp:38
std::ostringstream stream_
Definition: formatter.hpp:78
std::string str() const
Definition: formatter.hpp:64