C++ Logo

std-discussion

Advanced search

Re: 2 big problems with User Defined literals:

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Thu, 6 May 2021 10:09:37 -0400
On Thu, May 6, 2021 at 9:11 AM Andy Little via Std-Discussion
<std-discussion_at_[hidden]> wrote:
>
>
>
> 2 big problems with User Defined literals:
>
> 1)
>
> Why can't user defined literals have a namespace prefix?
> ...............................................................................................
>
> I have a units library I have used for many years.
>
> I would prefer to be able to say
>
> auto x = pqs::1_m; // x is a physical quantity representing 1 meter
>
> Then I could also make use of other units libraries in the same application. As it stands, if another units library also defines its own UDLs' in its headers then it will be very difficult to work with it.

We have functions that you could call, object typenames that you could
construct. Those work from namespaces just fine.

UDLs are for when space is at a premium, wordiness is really bad, and
the resultant meaning of the code ought to be obvious. Adding
namespaces to literals like this (even if the parser could do it)
means that you're willing to spell things out.

`pqs::meter(1)` is not that much shorter than `pqs::1_m`, and is a lot
more readable.

> 2)
>
> Clumsy handling of the types returned want smallest, not biggest
> .............................................................
>
> Other issue with user defined literals is their use of unsigned long long and long double. This can cause unnecessary narrowing conversion warnings since the biggest possible types end up being used. Exact opposite to what you want , (especially on a microcontroller) so now you need add ugly conversions everywhere. It would be nice to be able to tailor the return type depending on the value to the smallest type that fits. This could be done so easily if the value was made available to the UDL function ( e.g like a template parameter )

It can be made available as a template parameter. Unsynthesized UDLs
exist; they take the UDL as a variadic sequence of `char`s. They're
much harder to parse, but they are functional solutions.

The simplest solution here (that requires no language changes) is to
make a pair of library `consteval` template functions that take the
sequence of chars and returns a synthesized value; one for integers,
one for floats. This value would be `constexpr`, so it could be used
to determine the result type of the function.

Received on 2021-05-06 09:09:50