std.conv:to that does not throw?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Jan 30 04:44:02 UTC 2025


On Wednesday, January 29, 2025 8:00:43 PM MST H. S. Teoh via Digitalmars-d-learn wrote:
> > Unfortunately, there isn't currently a function like std.conv.to which
> > does not throw.
>
> I thought std.conv.parse* is supposed to fill that role?  Or am I
> remembering wrong?  They don't quite have the same level of convenience
> as .to, though.

No, parse is for converting only the first part of the input, with the idea
that you'll call it repeatedly to parse out multiple values, whereas to
converts the entire string. parse will still throw. It's just not going to
be under quite the same circumstances. And the fact that it parses what it
can and leaves the rest behind to be parsed next can make for some
surprising results sometimes, and you can easily end up with it converting
less than you would have wanted, which can get rather interesting when it
comes to reporting failures in a clean manner. parse has its uses, but
personally, I prefer to split the input and then convert each piece
individually rather than using parse. Either way, it's definitely not a
nothrow version of to. It's its own thing with its own quirks.

What we really need is something like tryTo that returns a Nullable which
has no value when the conversion fails, and then preferably, tryTo would
share its implementation with to (though that could get tricky, particularly
if you want to minimize how deep the templates go - even more so given that
to can't simply be a wrapper around tryTo if you want to provide any
information about why it failed like it currently does). But to's
implementation is probably going to get a major overhaul for Phobos v3
anyway to try to reduce how many template instantiations it incurs. Either
way, tryTo is definitely planned as part of Phobos v3.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list