C++11
offers user-defined literals. I've just started to play around with them, which made me wonder whether it would be possible to automatically add all SI multipliers to a single literal I define?
For example, if I define
Length operator "" _m(long double m) {
return Length(m); // Length in meters
}
where Length
is a subclass of some Units
base class, I would like to have a mechanism to automatically add (in the same spirit as boost operators) SI multipliers for all literals that return a Length
:
// these are added automatically when defining the literal "_m":
// Length in:
Length operator "" _Ym(long double Ym); // Yottameters
Length operator "" _Zm(long double Zm); // Zetameters
... // ...
... // ...
Length operator "" _km(long double km); // kilometers
Length operator "" _mm(long double mm); // millimeters
... // ...
... // ...
Length operator "" _zm(long double zm); // zeptometers
Length operator "" _ym(long double ym); // yoctometers
As far as I could see, aside from perhaps some macro magic, there is no way to do this automatically since all user-defined literals need an explicit definition.
..or am I overlooking something?
I do not think there is a way to do exactly what you are asking for without "bizarre macros". This is as far as I could get:
If bizarre macros are allowed, then something like the following should do the job:
Can't you use the
operator "" _m(const char *)
flavor as long as you're willing to parse the floats yourself? That makes it possible to write1234k_m
by calling out to a common SI-aware parser for your floating point values.