string_examples.cc (1420B)
1 /* 2 * this file demonstrates integrating ggformat with a string class 3 * 4 * compile me with "cl.exe string_examples.cc ggformat.cc" 5 * or "g++ -std=c++11 string_examples.cc ggformat.cc" 6 */ 7 8 #include "ggformat.h" 9 10 template< typename T > 11 T min( T a, T b ) { 12 return a < b ? a : b; 13 } 14 15 template< size_t N > 16 class str { 17 public: 18 str() { 19 clear(); 20 } 21 22 template< typename... Rest > 23 str( const char * fmt, const Rest & ... rest ) { 24 sprintf( fmt, rest... ); 25 } 26 27 void clear() { 28 buf[ 0 ] = '\0'; 29 length = 0; 30 } 31 32 template< typename T > 33 void operator+=( const T & x ) { 34 appendf( "{}", x ); 35 } 36 37 template< typename... Rest > 38 void sprintf( const char * fmt, const Rest & ... rest ) { 39 size_t copied = ggformat( buf, N, fmt, rest... ); 40 length = min( copied, N - 1 ); 41 } 42 43 template< typename... Rest > 44 void appendf( const char * fmt, const Rest & ... rest ) { 45 size_t copied = ggformat( buf + length, N - length, fmt, rest... ); 46 length += min( copied, N - length - 1 ); 47 } 48 49 const char * c_str() const { 50 return buf; 51 } 52 53 private: 54 char buf[ N ]; 55 size_t length; 56 }; 57 58 template< size_t N > 59 void format( FormatBuffer * fb, const str< N > & buf, const FormatOpts & opts ) { 60 format( fb, buf.c_str(), opts ); 61 } 62 63 int main() { 64 str< 256 > a( "hello {-10}:", "world" ); 65 a += " "; 66 a += 1; 67 a += " "; 68 a += 1.2345; 69 a += " "; 70 a += false; 71 a.appendf( ". {} w{}rld", "goodbye", 0 ); 72 73 ggprint( "{}\n", a ); 74 return 0; 75 }