X-Git-Url: http://git.tdb.fi/?p=libs%2Fcore.git;a=blobdiff_plain;f=source%2Fstrings%2Fformatter.h;fp=source%2Fstrings%2Fformatter.h;h=cde508bac9740aaf9c0064166436b38354a3d7f4;hp=0000000000000000000000000000000000000000;hb=b42ed73a1b241c0e93ee03c43c4584b41c549bac;hpb=5b1368cb791cab043f0435628cacbaff36e39b7b diff --git a/source/strings/formatter.h b/source/strings/formatter.h new file mode 100644 index 0000000..cde508b --- /dev/null +++ b/source/strings/formatter.h @@ -0,0 +1,70 @@ +/* $Id$ + +This file is part of libmspstrings +Copyright © 2006-2007 Mikko Rasa +Distributed under the LGPL +*/ + +#ifndef MSP_STRINGS_FORMATTER_H_ +#define MSP_STRINGS_FORMATTER_H_ + +#include +#include "lexicalcast.h" + +namespace Msp { + +/** +Printf-like string formatter class. +*/ +class Formatter +{ +private: + std::string fmt; + std::string::iterator pos; + std::string result; + +public: + Formatter(const std::string &); + + /** Extracts the next conversion from the format string and formats the + given value with it. Will throw if no more conversions are found. */ + template + Formatter &operator()(const T &a) + { + result += lexical_cast(a, get_conversion()); + advance(); + return *this; + } + + const std::string &str() const; +private: + void advance(); + Fmt get_conversion(); +}; + +inline Formatter format(const std::string &f) +{ return Formatter(f); } + +template +inline std::string format(const std::string &f, const A1 &a1) +{ return Formatter(f)(a1).str(); } + +template +inline std::string format(const std::string &f, const A1 &a1, const A2 &a2) +{ return Formatter(f)(a1)(a2).str(); } + +template +inline std::string format(const std::string &f, const A1 &a1, const A2 &a2, const A3 &a3) +{ return Formatter(f)(a1)(a2)(a3).str(); } + +template +inline std::string format(const std::string &f, const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4) +{ return Formatter(f)(a1)(a2)(a3)(a4).str(); } + +template +inline std::string format(const std::string &f, const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4, const A5 &a5) +{ return Formatter(f)(a1)(a2)(a3)(a4)(a5).str(); } + +} // namespace Msp + +#endif