]> git.tdb.fi Git - libs/core.git/blob - source/strings/format.h
6d8f739a436c3abaa8fdbbbdc7292e5dfb803d1d
[libs/core.git] / source / strings / format.h
1 #ifndef MSP_STRINGS_FORMAT_H_
2 #define MSP_STRINGS_FORMAT_H_
3
4 #include <string>
5 #include "lexicalcast.h"
6
7 namespace Msp {
8
9 /**
10 Printf-like string formatter class.
11 */
12 class Formatter
13 {
14 private:
15         std::string fmt;
16         std::string::iterator pos;
17         std::string result;
18
19 public:
20         Formatter(const std::string &);
21
22         /** Extracts the next conversion from the format string and formats the
23         given value with it.  Will throw if no more conversions are found. */
24         template<typename T>
25         Formatter &operator()(const T &a)
26         {
27                 result += lexical_cast(a, get_conversion());
28                 advance();
29                 return *this;
30         }
31
32         /** Returns the result of the formatting operation.  Will throw if not
33         enough values have been fed to the formatter. */
34         const std::string &str() const;
35
36 private:
37         /** Advances the iterator to the next conversion, adding literal characters
38         to the result.  The iterator is left at the second character of the
39         conversion (i.e. after the %). */
40         void advance();
41
42         /** Reads the next conversion from the format string and returns a
43         corresponding Fmt object. */
44         Fmt get_conversion();
45 };
46
47 inline Formatter format(const std::string &f)
48 { return Formatter(f); }
49
50 template<typename A1>
51 inline std::string format(const std::string &f, const A1 &a1)
52 { return Formatter(f)(a1).str(); }
53
54 template<typename A1, typename A2>
55 inline std::string format(const std::string &f, const A1 &a1, const A2 &a2)
56 { return Formatter(f)(a1)(a2).str(); }
57
58 template<typename A1, typename A2, typename A3>
59 inline std::string format(const std::string &f, const A1 &a1, const A2 &a2, const A3 &a3)
60 { return Formatter(f)(a1)(a2)(a3).str(); }
61
62 template<typename A1, typename A2, typename A3, typename A4>
63 inline std::string format(const std::string &f, const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4)
64 { return Formatter(f)(a1)(a2)(a3)(a4).str(); }
65
66 template<typename A1, typename A2, typename A3, typename A4, typename A5>
67 inline std::string format(const std::string &f, const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4, const A5 &a5)
68 { return Formatter(f)(a1)(a2)(a3)(a4)(a5).str(); }
69
70 } // namespace Msp
71
72 #endif