]> git.tdb.fi Git - libs/core.git/blob - source/strings/format.h
db74bf9560788f3bbce4b0673cd5f7b3076ba2fc
[libs/core.git] / source / strings / format.h
1 /* $Id$
2
3 This file is part of libmspstrings
4 Copyright © 2006-2007 Mikko Rasa
5 Distributed under the LGPL
6 */
7
8 #ifndef MSP_STRINGS_FORMAT_H_
9 #define MSP_STRINGS_FORMAT_H_
10
11 #include <string>
12 #include "lexicalcast.h"
13
14 namespace Msp {
15
16 /**
17 Printf-like string formatter class.
18 */
19 class Formatter
20 {
21 private:
22         std::string fmt;
23         std::string::iterator pos;
24         std::string result;
25
26 public:
27         Formatter(const std::string &);
28
29         /** Extracts the next conversion from the format string and formats the
30         given value with it.  Will throw if no more conversions are found. */
31         template<typename T>
32         Formatter &operator()(const T &a)
33         {
34                 result += lexical_cast(a, get_conversion());
35                 advance();
36                 return *this;
37         }
38
39         const std::string &str() const;
40 private:
41         void advance();
42         Fmt get_conversion();
43 };
44
45 inline Formatter format(const std::string &f)
46 { return Formatter(f); }
47
48 template<typename A1>
49 inline std::string format(const std::string &f, const A1 &a1)
50 { return Formatter(f)(a1).str(); }
51
52 template<typename A1, typename A2>
53 inline std::string format(const std::string &f, const A1 &a1, const A2 &a2)
54 { return Formatter(f)(a1)(a2).str(); }
55
56 template<typename A1, typename A2, typename A3>
57 inline std::string format(const std::string &f, const A1 &a1, const A2 &a2, const A3 &a3)
58 { return Formatter(f)(a1)(a2)(a3).str(); }
59
60 template<typename A1, typename A2, typename A3, typename A4>
61 inline std::string format(const std::string &f, const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4)
62 { return Formatter(f)(a1)(a2)(a3)(a4).str(); }
63
64 template<typename A1, typename A2, typename A3, typename A4, typename A5>
65 inline std::string format(const std::string &f, const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4, const A5 &a5)
66 { return Formatter(f)(a1)(a2)(a3)(a4)(a5).str(); }
67
68 } // namespace Msp
69
70 #endif