mp-units icon indicating copy to clipboard operation
mp-units copied to clipboard

Programmatic generation of quantities/parsing of units from string

Open jagot opened this issue 2 months ago • 2 comments

I want to let the user enter inputs in e.g. a text file, specifying the units of various parameters.

A valid input could be

distance = 1 m
velocity = 2 m/s

or

distance = 2 cm
velocity = 8 nm/fs

which I then would read and parse internally. For this particular example, I would only care that distance is a length, and that velocity is length per time.

How can I accomplish this? As far as I understand, the type of quantity is set at compile time, so I cannot build up the unit of the quantity iteratively:

quantity v = 8;
v *= nm;
v /= fs;

which is the approach I would try, having parsed the string "nm/fs" into an AST.

It boils down to me wanting to have runtime checks of units. Internally, I work with dimension-less quantities, but want to support converting to these from various possible choices of units.

jagot avatar Oct 17 '25 09:10 jagot

Hi! It seems that you need something like #483. Unfortunately, for now, those are not supported or planned. You may try with a std::variant of supported units, but I agree this is not the most user-friendly solution.

mpusz avatar Oct 19 '25 19:10 mpusz

Aha. I see #674 was basically asking for the same thing. For me, it is almost vital functionality, to avoid unit conversion errors for the user. However, I do see that it is maybe orthogonal to this project's main goal of compile-time assertion, something which is of lower priority to myself.

jagot avatar Oct 19 '25 22:10 jagot