Question

A quick question: why doesn't C++11 offer a "user-" (really, standard library) defined literal for creating a std::string, such as

auto str = "hello world"s; // str is a std::string

Like C++, Objective-C supports both C-style strings and a more user-friendly library type NSString; however, unlike C++, nobody ever gets confused between the two, because it's trivial to create an NSString by prefixing a string literal with @. In fact, it's rare to see Objective-C code where a literal doesn't have the @ prefix. Everybody just knows that's the way to do it, uses NSString and gets on with it.

C++11 user-defined literals would allow this, and in fact the UDL section on Stroustrup's C++11 FAQ uses exactly this example. Furthermore, UDLs without a leading underscore are reserved, so there would be no problem in allowing a plain s as above -- there's no possibility of it clashing with anything else.

Perhaps I'm missing something, but it seems like this would be a very valuable and risk-free addition to the language, so does anybody know why C++11 doesn't offer it? Is it likely to appear in C++14?

Was it helpful?

Solution

User-defined literals were new enough in C++11 that this wasn't included, but it is in C++14( in §21.7, in case anybody cares). And yes, it uses s as the suffix. The precise result type depends on the type of the string literal itself -- a "narrow" literal gives an std::string, a u16 literal gives a u16string, and a u32 literal gives a u32string. Oh, and yeah, if you insist on using a wide string literal it'll produce a wstring.

Note that the s suffix is also used to mean seconds (defined in <chrono>) but there's no real conflict between the two--s on a string literal means a string, and s on a number means seconds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top