C++ Logo

std-discussion

Advanced search

Re: 2 big problems with User Defined literals:

From: John McFarlane <john_at_[hidden]>
Date: Sun, 16 May 2021 15:45:49 +0100
On Fri, 7 May 2021 at 15:09, Andy Little via Std-Discussion <
std-discussion_at_[hidden]> wrote:

> > UDLs are for when space is at a premium, wordiness is really bad, and
> > the resultant meaning of the code ought to be obvious.
>
> Sure, but that is basically always.
>

Agreed. If what you're trying to express is rich, expect a few more
keystrokes. I'm not convinced -- given how compact they already are -- that
UDLs are particularly good at conveying much information. E.g. you need to
already know that `sv` means string view. UDLs are not an accessible point
of discovery about a type, but an abbreviation to be introduced rarely and
used often.

>
> > Adding namespaces to literals like this (even if the parser could do it)
> > means that you're willing to spell things out.
>
> UDLs is a potentially nice language feature, but is inflexible. Currently
> UDLs can't be qualified, so they can only be used in global namespace.
> The problem as shown by the ad hoc rule that UDLs without underscore are
> reserved.
> Yet already there are potential collisns in std namespace between units
> libray proposal
> http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p1935r2.html
> and std::chrono literals
>

The namespace collisions aren't as severe as the limit of one suffix per
literal. This reduces expressivity so much that -- even in places where
you'd really like to see them -- UDLs should be few. We'd all love the
"2.6cm" from our school textbooks to translate to code, but textbooks
aren't strongly typed.

Units are a good example. A generally-useful units library exposes the rep
type in the API of its wrappers: you may wish to use a non-fundamental
type, or otherwise control how the number is held. If you try to express a
combination of details, you're already in trouble at "an int representing
metres" versus "a float representing seconds".

For this reason I recommend against defining UDLs for units at all.
Providing the user with a solution that works in toy examples but doesn't
scale might be worse than nothing at all. The `299'792.458L * my::km /
my::s` approach seems more promising to me.

Cheers,
John

Received on 2021-05-16 09:46:03