]> git.tdb.fi Git - libs/core.git/blob - source/formatter.h
Initial upload
[libs/core.git] / source / formatter.h
1 #ifndef MSP_STRINGS_FORMATTER_H_
2 #define MSP_STRINGS_FORMATTER_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 public:
15         Formatter(const std::string &);
16
17         /**
18         Extracts the next conversion from the format string and formats the given
19         value with it.  Will throw if no more conversions are found.
20         */
21         template<typename T>
22         Formatter &operator()(const T &a)
23         {
24                 result+=lexical_cast(a, get_conversion());
25                 advance();
26                 return *this;
27         }
28
29         const std::string &str() const;
30 private:
31         std::string fmt;
32         std::string::iterator pos;
33         std::string result;
34
35         void advance();
36         Fmt  get_conversion();
37 };
38
39 inline Formatter format(const std::string &f)
40 { return Formatter(f); }
41
42 template<typename A1>
43 inline std::string format(const std::string &f, const A1 &a1)
44 { return Formatter(f)(a1).str(); }
45
46 template<typename A1, typename A2>
47 inline std::string format(const std::string &f, const A1 &a1, const A2 &a2)
48 { return Formatter(f)(a1)(a2).str(); }
49
50 template<typename A1, typename A2, typename A3>
51 inline std::string format(const std::string &f, const A1 &a1, const A2 &a2, const A3 &a3)
52 { return Formatter(f)(a1)(a2)(a3).str(); }
53
54 template<typename A1, typename A2, typename A3, typename A4>
55 inline std::string format(const std::string &f, const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4)
56 { return Formatter(f)(a1)(a2)(a3)(a4).str(); }
57
58 template<typename A1, typename A2, typename A3, typename A4, typename A5>
59 inline std::string format(const std::string &f, const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4, const A5 &a5)
60 { return Formatter(f)(a1)(a2)(a3)(a4)(a5).str(); }
61
62 } // namespace Msp
63
64 #endif