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