useful namespaces in c++ other than 'std'
Whenever I read books about C++, I find an example of "using开发者_运维问答 namespace std".
I would like to know if any other namespaces are present in C++ which are useful?
boost.
std::tr1. (Technical Report 1)
But using namespace std;
is not a good idea, and especially not in header files. It's 5 extra characters every time you use it, for significantly clearer code and less clashes.
Everything in the C++ Standard Library is in the std
namespace (or a nested namespace under std
).
Other libraries use other namespaces, of course. You'll want to consult the documentation of whatever other libraries you are using to determine what namespace(s) they use.
That said, using directives are generally A Bad Idea. It's much better to use using declarations to use individual names from a namespace. This is especially important for the std
namespace. There are many commonly used names in the std
namespace and it's easy to run into hard-to-solve issues where you try to refer to your own function or class and accidentally refer to a Standard Library function or class. For example, this is bad:
using namespace std;
cout << "Hello world" << endl;
This is better:
using std::cout;
using std::endl;
cout << "Hello world" << endl;
In my opinion, code is usually cleaner when you use fully qualified names throughout your program; this makes it clearer where entities are coming from and leaves less room for mistakes:
std::cout << "Hello world" << std::endl;
(There are exceptions to all of these rules, of course. For example, when using std::bind
, it's a beating to use std::placeholders::_1
and its friends. It's much easier to read code that uses using std::placeholders;
and then just refers to _1
, _2
, etc. The using directive should be inside of the function, though, not at namespace scope.)
I'm surprised no one mentioned the std::rel_ops
namespace. It defines operator!=
, operator>
, operator<=
and operator>=
.
You can bring those in scope by a using directive or declaration and define a operator<
and operator==
for your type. The operators provided by std::rel_ops
then work in terms of these two.
This is the namespace for the C++ standard library. AFAIK this is the only namespace you have "out-of-the-box". All others you have to define yourself or you get them from other libraries.
All the files in the C++ standard library declare all of its entities within the std namespace. You will encounter other namespaces only if you are using a third party library (like boost), or defining your own namespaces.
精彩评论