Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator suffix for std::string in c++14

Tags:

I install Clang 3.4, and test suffix operator for string literal ""s.

#include <string>  //1. using namespace std; // without compile error. //2. using std::operator ""s; // or without it compile error, too. // for success compiles, need 1. or 2. line.  int main() {     auto s = "hello world"s;  } 

If I comment 1 and 2 , I get compile error. But I know in big projects 1.-method is bad, and 2.-method is stranger.

QA: Can I use operator ""s without any writing using namespace std and using std::operator ""s ?

like image 360
Khurshid Avatar asked Jan 10 '14 17:01

Khurshid


People also ask

What is an std::string?

The std::string type is the main string datatype in standard C++ since 1998, but it was not always part of C++. From C, C++ inherited the convention of using null-terminated strings that are handled by a pointer to their first element, and a library of functions that manipulate such strings.

What is string :: Size_type?

The std::string type defines size_type to be the name of the appropriate type for holding the number of characters in a string. Whenever we need a local variable to contain the size of a string, we should use std::string::size_type as the type of that variable.

What is a string literal C++?

String literals. A string literal represents a sequence of characters that together form a null-terminated string. The characters must be enclosed between double quotation marks.

How do you insert std::string?

In C++, you should use the string header. Write #include <string> at the top of your file. When you declare a variable, the type is string , and it's in the std namespace, so its full name is std::string .


1 Answers

Wrapping up the comments:

You have to explicitly pull in those operators with using. This is what is intended by the standard. You should consider to pull in only what you need, either

using namespace std::literals; 

or

using namespace std::literals::string_literals; 

depending on your needs, the latter being preferable in case of doubt (only pull in what you need, not more). As with all using declarations or directives, you want to limit them to the smallest scope that is practical.

The reason behind the need to pull the operators in explicitly is that the suffixes might be re-used in future extensions in different contexts.

like image 169
Daniel Frey Avatar answered Sep 21 '22 06:09

Daniel Frey