2

I just saw a new C++ syntax like:

x = "abc"s;

From context I guessed that this means x was assigned a string "abc", I would like to know the name of this new syntax, and is there any similar syntax in C++1z?

dguan
  • 1,023
  • 1
  • 9
  • 21

1 Answers1

11

Yes, they've been around since C++11. They're called user-defined literals. This specific literal was standardized in C++14, however, it is easy to roll your own.

#include <string>
#include <iostream>

int main()
{
    using namespace std::string_literals;

    std::string s1 = "abc\0\0def";
    std::string s2 = "abc\0\0def"s;
    std::cout << "s1: " << s1.size() << " \"" << s1 << "\"\n";
    std::cout << "s2: " << s2.size() << " \"" << s2 << "\"\n";
}

For example, to make your own std::string literal, you could do (note, all user-defined literals must start with an underscore):

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

To use the example I gave, simply do:

#include <iostream>
#include <string>

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


int main(void)
{
    auto s = "My message"_s;
    std::cout << s << std::endl;
    return 0;
}
Alex Huszagh
  • 13,272
  • 3
  • 39
  • 67