Question

I'm wondering why I can't 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 couldn't find literal operator operator"" _km.to_miles unless I wrap 27_km in parentheses:

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

By my reading of section 2.14.8 of the standard, a UDL suffix can't contain a period, so why are the compilers parsing the code like this? Are they correct or is it a bug?

EDIT: You can see a full example (with different UDL and method names) here: http://ideone.com/rvB1pk

Était-ce utile?

La solution 2

This may be a lexer issue. The user-defined literal is to be tokenized as a single chunk - number plus suffix is one whole token. In the case of numeric literals the characters it is allowed to slurp up includes the decimal '.'. Lookup pp-number: section 2.10 - lex.ppnumber in the latest draft of the standard. Walk through how the preprocessor (lexer) would scan 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 freaky (floating-point) number. Then later, during the number parsing phase we see digit, digit, identifier-nondigit... At that point, the remainder from '-' onwards is handed off as a suffix identifier.

Remember that number literals are interpreted after the preprocessor tokenizes.

I think this is actually not a defect.

Autres conseils

The suffix for a UDL is supposed to be a normal identifier (with a leading underscore), so it looks like a bug to me.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top