It is possible to pass an empty string literal to a user-defined raw literal operator?

257 Views Asked by At

Consider the following simple user-defined raw literal operator:

#include <string>

std::string operator""_s(const char* s) {
  return s;
}

which gives us another easier way to generate std::strings with only integer characters:

auto s1 = 012345_s; // s1 is "0123456"s
auto s2 = 0_s;      // s2 is "0"s

But is it possible to generate empty string using this raw literal operator?

auto s3 = ???_s;    // s3 is ""s
1

There are 1 best solutions below

4
m88 On

The single-argument form T operator""_s(const char* s) is just a fallback case for integers and floating-point types.
The proper way to handle a user-defined string literal is via T operator""_s(const CharT* s, size_t sz).

#include <string>

std::string operator""_s(const char* s) {
  return s;
}

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

int main()
{
    auto s1 = 012345_s;
    auto s2 = 0_s;  
    auto s3 = ""_s;
}

https://godbolt.org/z/qYM1WaKrh