Which user-defined-literals are predefined by the

2019-04-21 05:12发布

问题:

My question sounds like a contradiction, but I don't know how else to refer to the new literal syntax other than user-defined-literal.

std::string operator "" s ( const char* str, size_t len )
{
   return std::string( str, len );
}

assert( "foo"s == "bar"s );

I remember hearing that user defined literals should start with an _ prefix. That would imply that the library defines some non-prefixed literals for us.

Does the standard provide some UDLs in the the standard library?
If yes, what are they?

回答1:

The language already use regular literals suffixes, for example 1U.

It would become ambiguous if you were to use U as a user-defined-literal, thus the recommendation.

integer-suffix: u, U, l, L, ll, LL

floating-suffix: f, F, l, L



回答2:

The standard library actually defines no user defined literals. We would perhaps have expected complex numbers, but no.

On the other hand, there is also a proposal to remove them again

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3250.html

so we don't yet know what happens.



回答3:

In contrast to @Matthieu's answer, the FIDS says the following under 2.14.8 [lex.ext] p1:

If a token matches both user-defined-literal and another literal kind, it is treated as the latter.
[ Example: 123_km is a user-defined-literal, but 12LL is an integer-literal. — end example ]

So even if you define those literals, the predefined ones are taken and there is no ambiguity.



回答4:

No standard library components have staked a claim on a user-defined literal. @Bo mentioned complex as a possibility.

Another is bitset:

template<char... Bits>
  inline constexpr std::bitset<sizeof...(Bits)>
  operator"" bits()
  {
    return std::bitset<sizeof...(Bits)>((char []){Bits..., '\0'});
  }

I predict there will be proposals for literal operators for various library components in the upcoming library TR2 enhancements.

I anticipate some collisions over the suffix namespace. You can declare literal operators in a namespace and prevent multiple ambiguous definitions but you can't distinguish the actual suffixes by namespace in an actual literal. We'll see.