Search code examples
c++templatesc++11user-defined-literals

Literal operator template: why not string?


Once again, while replying to another question, I forgot (my fault) that literal operator templates are picked up from the set of declarations only when integer or floating literals are found.

As an example:

template <char... C>
constexpr int operator "" _x() {
    return 0;
}

It can be used as 10_x, but it cannot be used neither as foo_x nor as "foo"_x.

Apart for the obvious reason that is because the standard says that, what's the technical reason (if any) for which they are not considered when dealing with string literals?

I found also a proposal for that (well, not exactly the same, but it gives an idea), but still that is not an option.
What prevents them to be used for strings?


Solution

  • There where complications involving character sets and encoding and other such mess. What happens if the character set encoding differs between runtime and compile time, what happens if there are multiple ways to encode the same character, does the string being utf-8 encoded vs a different encoding do anything? Do you translate to the runtime character set, or not?

    Maybe there are easy answers; but there was enough complication that the proposers went "ok, we'll cut this" and the literals got into the standard.

    The characters permitted for floating point and integral literals where limited, and did not have this problem.

    But you linked to a document that linked to N2750, and which directly stated:

    there may be demand for a "raw" form of string literal, in which

    "Hello, " L"Worl\u0044!"
    

    is distinguishable from

    L"Hello, World!"
    

    but this interacted badly with phases of translation, and no compelling use cases for this feature were known.