I'm starting to use the Karma generate feature to convert double to char with a sprintf like functionality. For that I'm using the following example:
template <typename T>
class double3_policy : public boost::spirit::karma::real_policies<T>
{
public:
template <typename T>
static unsigned int precision(T)
{
return 3;
}
};
typedef boost::spirit::karma::real_generator<double, double3_policy<double> > double3_type;
double3_type const double3 ;
using boost::spirit::karma::left_align;
using boost::spirit::karma::generate;
char *p = buffer;
generate(p, '[' << left_align(14)[double3] << left_align(14)[double3] << ']', 12345.000, 22/7.0);
*p = '\0';
The example works fine, but the precision method is static, and I not realized how to set that value dynamically. I want to specify the precision for each use, changing that at execution time. I don't mind to create all generators at start, because I want a defined number of precisions.
The problem is that I don't believe I have to create a class for each precision number when the only difference between them is a returning number. I tried to compile the class with a member method (if this was a member precision method that would be enough for me), and I think I'm stuck at this class method problem.
How can I create generator objects with diferent precisions and just use them without create more then one class? If I can use just one generator just changing a property would be even better.
If anyone had the same problem and can share the solution will be very helpful.
Thanks,
Karma generators are all about specifying grammars using (compile-time!) expression templates, like an embedded DSL.
This does indeed make it less than applicable for dynamic format specifications.
I'd suggest to use
The only way I can see this work with Karma is by creating a custom directive for real-printing which takes the precision as an extra argument. It's not worth it (and it will kill the only benefit you had for using Karma here: performance).