commit ab41492b069ccc7db90d91742d7cf97b0c4789fb
parent acae389b69e0e4de6ea3e8fefc530d5e8bd25ccc
Author: Michael Savage <mikejsavage@gmail.com>
Date: Fri, 25 Aug 2017 21:07:01 +0100
Document how to use ggformat with std::string
Diffstat:
1 file changed, 25 insertions(+), 0 deletions(-)
diff --git a/README.md b/README.md
@@ -143,6 +143,31 @@ If you have a huge type and don't feel like writing a wall of `format`,
see `Thing` in basic_examples.cc.
+## Dynamic allocation (std::string, asprintf, etc)
+
+`ggformat( NULL, 0, ... );` returns the number of bytes required to hold
+the formatted string. With that it's easy to integrate ggformat with
+your favourite dynamic string solution. For example, ggformat with
+std::string:
+
+```cpp
+template< typename... Rest >
+std::string ggformat_to_string( const char * fmt, Rest... rest ) {
+ size_t space_required = ggformat( nullptr, 0, fmt, rest... );
+
+ if( space_required + 1 < space_required )
+ throw std::overflow_error( "formatted string is too long" );
+
+ std::string result;
+ result.resize( space_required + 1 ); // + 1 so there's space for the null terminator...
+ ggformat( &result[ 0 ], space_required + 1, fmt, rest... );
+ result.resize( space_required ); // ...and then trim it off
+
+ return result;
+}
+```
+
+
## Other stuff
Since this is C++ you can and should wrap `ggformat` in a string class