namespace usage
I'm trying to start using namespaces the correct (or at least best) way.
The first thing I tried to do was to avoid pu开发者_运维问答tting using namespace xxx;
at the beginning of my files. Instead, I want to using xxx::yyy
as locally as possible.
Here is a small program illustrating this :
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
using std::cout;
using std::endl;
srand(time(0));
for(int i=0; i<10;++i)
cout << rand() % 100 << endl;
return 0;
}
If I omit the lines using std::cout;
or using std::endl
, the compiler will complain when I'm trying to use cout
or endl
.
But why is this not needed for srand
, rand
and time
? I'm pretty sure they are in std
, because if I try to specifically pour std::
in front of them, my code is working fine.
If you use cstdlib et al. the names in them are placed in both the global and the std:: namespaces, so you can choose to prefix them with std:: or not. This is seen as a feature by some, and as a misfeature by others.
If you really want to know, take a close look at the ctime
and cstdlib
headers. They were built backwards-compatible.
Note: all this using
vs. using namespace
business is about readability. If your IDE would allow to just not show the namespaces when you don't want to see them, you wouldn't need these constructs...
I prefer to omit using and just have the std::cout every time just to maintain readability. although this is probably only useful in larger projects
As long as we on the subject, there's also a thing called Koenig Lookup which allows you to omit a namespace identifier before a function name if the arguments it take come from the same namespace.
For example
#include <iostream>
#include <algorithm>
#include <vector>
void f(int i){std::cout << i << " ";}
int main(int argc, char** argv)
{
std::vector<int> t;
// for_each is in the std namespace but there's no *std::* before *for_each*
for_each(t.begin(), t.end(), f);
return 0;
}
Well, it's not related directly but I though it may be useful.
精彩评论