Combining a user-defined literal with a method call

I am wondering why I cannot write code like this:

constexpr double radius = 27_km.to_miles(); // _km returns Distance instance // which has to_miles() 

Both GCC 4.8.1 and Clang 3.4 complain that they could not find the literal operator operator"" _km.to_miles unless I 27_km in parentheses:

 constexpr double radius = (27_km).to_miles(); // fine 

In my reading, in section 2.14.8 of the standard, the UDL suffix cannot contain a period, so why do compilers deal with such code? Are they correct or is this a mistake?

EDIT: here you can see the full example (with different UDL names and methods): http://ideone.com/rvB1pk

+6
source share
2 answers

This may be a lexer problem. The user literal should be designated as one fragment - the number plus suffix is ​​one single token. In the case of numeric literals, characters that are allowed to clone include a decimal number. Lookup pp-number: section 2.10 - lex.ppnumber in the last draft of the standard. See how the preprocessor (lexer) scans the token:

 30_au.to_light_years() digit digit identifier-nondigit . identifier-nondigit x 14 ( breaks the spell 

So, the preprocessor sees 30_au.to_light_years as a big fancy (floating point) number. Then, during the parsing phase, we see digit, digit, identifier-nondigit... At this point, the remainder of '-' is passed forward as the suffix identifier.

Remember that number literals are interpreted after the preprocessor performs tokenization.

I think this is not really a flaw.

+2
source

The suffix for UDL should be a normal identifier (with leading underscore), so it looks like an error to me.

+3
source

Source: https://habr.com/ru/post/956042/


All Articles