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::
?
For starters there is a difference in name lookup for qualified and unqualified names.
Consider for example the following program.
#include <iostream>
class A
{
private:
int x = 10;
public:
operator int() const { return x; }
friend void f( const A & )
{
std::cout << "f( const A & )\n";
}
};
void f( int )
{
std::cout << "f( int )\n";
}
int main()
{
const A a;
f( a );
::f( a );
return 0;
}
The program output is
f( const A & )
f( int )
Secondly using using directives can result in name collisions or selecting a wrong function due to the overload resolution.
Apart of this the code can be less readable because the reader will not know for example whether endl
is std::endl
or a user defined function defined in some namespace that is included in the name lookup due to numerous using directives.
There are situations when you need to use an explicit or an implicit using directive.
For example if you want to use declarations from the namespace std::placeholders
or when you want to declare an inline namespace. But the scope of these directive is usually very limited. Another example is using using declarations. But again try to make their scopes as small as possible.