Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define a negative UDL in c++11 (are they disallowed?)?

I'm not even sure if negative User-Defined Literals are allowed. If not, why were they left out?

For example, I would like to use:

auto money_i_owe_jack = -52_jpy;

This is what I tried using gcc 4.7.2:

constexpr int64_t operator "" _jpy(long long l)
{
  return static_cast<int64_t>(l);
}

ERROR

Test_udl.cpp:60:47: error: ‘constexpr int64_t operator"" _jpy(long long int)’ has invalid argument list
like image 718
kfmfe04 Avatar asked Feb 20 '13 05:02

kfmfe04


2 Answers

Whether user-defined or otherwise, integer and floating point literals are always positive.

The reason is fairly simple: if you allow negative literals, lexing becomes context dependent. That is, when faced with something like - 10, the lexer can't just look at that text in isolation and know whether it should be treated as two separate tokens (- and 10) or one (-10). If you always treated it as a single token, then something like a - 10 would result in <a> and <-10> (i.e., <identifier><literal>, which isn't a legitimate sequence in C++ (or most other programming languages).

To get around that, the parser could feed some context to the lexer, telling at any given moment whether to expect (for example) an operator or an operand, so it would know that if it was to produce an operator, the - should be treated as a token of its own, but if an operand was expected, -10 would be a single token.

It's generally easier to have a single rule that's always followed though, and one that works is that the - is always an operator, and a literal can't include a - at all.

like image 69
Jerry Coffin Avatar answered Oct 20 '22 04:10

Jerry Coffin


Integer literals need to be accepted as unsigned long long. The negative sign is not part of the literal, it is applied after the fact, to the returned value.

constexpr int64_t operator "" _jpy(unsigned long long l)
{
  return static_cast<int64_t>(l);
}
like image 43
Benjamin Lindley Avatar answered Oct 20 '22 04:10

Benjamin Lindley