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

独自空忆成欢 提交于 2019-12-21 10:55:34

问题


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

回答1:


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);
}



回答2:


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.



来源:https://stackoverflow.com/questions/14972812/how-do-i-define-a-negative-udl-in-c11-are-they-disallowed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!