Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using string literals without using namespace std

Tags:

c++

c++11

There's recommendation in C++ community to not to use using namespace std;. But suppose you want to use string literals e.g. auto s = "dummy"s;. Not using using namespace std; cause to failed compile. What is the solution?

like image 446
E. Vakili Avatar asked Aug 15 '16 06:08

E. Vakili


People also ask

What happens if you dont use namespace std?

If we don't want to use this line of code, we can use the things in this namespace like this. std::cout, std::endl. If this namespace is not used, then computer finds for the cout, cin and endl etc.. Computer cannot identify those and therefore it throws errors.

Is using namespace std compulsory?

why is it compulsory to use using namespace std ? It isn't. In fact, I would recommend against it. However, if you do not write using namespace std , then you need to fully qualify the names you use from the standard library.

Can you write a code without declaring using namespace std?

If you don't declare a namespace for a library, you'll be retrieving the inner functions like so: `std::cout`. By declaring a namespace, we are just making the calls to the functions easier to write.

What happens if you remove using namespace std from your code?

Thus, removing using namespace std; changes the meaning of those unqualified names, rather than just making the code fail to compile. These might be names from your code; or perhaps they are C library functions.


1 Answers

operator""s is in 2 inlined namespaces in namespace std. It basically looks like this:

namespace std {     inline namespace literals     {         inline namespace string_literals         {             //operator""s implementation             //...         }     } } 

So, to only get the string literals, use using namespace std::string_literals;.

Alternatevely, if you want to include every literal - including the string literals (like s for seconds if you include chrono, ...): using namespace std::literals;.

Depending on the situation, you might also consider using:

using std::string_literals::operator""s; 

instead of importing every name from that namespace.

Note that you should still not include it in a header, at global level (but you can do it inside inline or member functions or namespaces you control)

like image 74
Rakete1111 Avatar answered Sep 26 '22 08:09

Rakete1111