Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the name of this new c++ syntax? [duplicate]

Tags:

c++

c++11

c++17

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?

like image 729
dguan Avatar asked Jan 01 '26 10:01

dguan


1 Answers

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;
}
like image 191
Alexander Huszagh Avatar answered Jan 04 '26 03:01

Alexander Huszagh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!