Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespace information compromises the readability in C++

I'm new to C++ and had a background in C. The one thing which is quite difficult for me to adopt is to frequently use scope operator e.g. std:: Well, i'd avoid it usage by putting using namespace std at the start of my source code but a lot of people doesn't use this method as they think this may bite them in future.

Plus, the visual-studio also shows error/warning messages along scope operator e.g.

cannot convert from 'std::vector<int,std::allocator<_Ty>> *' to 'std::shared_ptr<std::vector<int,std::allocator<_Ty>>>'

Though the above message is verbose but its such a pain to read it (?). I think it can be simple to read if it was in this form

cannot convert from 'vector<int,allocator<_Ty>> *' to 'shared_ptr<vector<int,allocator<_Ty>>>'

1) Why everyone is using std::, even for cout, cin, endl ? Why would anyone use the labels for some other purpose anyways?

2) Is their a workaround in Visual studio to not show me error/messages/syntax-highlights with a prefix std:: ?

like image 292
Nouman Tajik Avatar asked Jan 26 '23 10:01

Nouman Tajik


1 Answers

Although, as pointed out in the comments, code like using namespace std; is considered bad practice, you can avoid repeated use of the namespace prefix in code like std::cout, by specifying individual scoped elements in using statements.

Something like this:

using std::cout;  //
using std::cin;   // You can, from then on, just use 'cout', 'cin' and 'endl'
using std::endl;  //

For very common elements, like those listed in the above code, you can put the relevant using lines in a header file - typically, your 'global' header that you use to build your precompiled header.

like image 95
Adrian Mole Avatar answered Feb 05 '23 10:02

Adrian Mole