Namespaces provide a method for preventing name conflicts in large projects.
Symbols declared inside a namespace block are placed in a named scope that prevents them from being mistaken for identically-named symbols in other scopes.
Multiple declarations of namespaces with the same name are allowed, resulting in a namespace including all symbols from all such declarations.
[edit] Syntax
|
namespace ns_name { declarations }
|
(1)
|
|
|
inline namespace ns_name { declarations }
|
(2)
|
(since C++11)
|
|
namespace { declarations }
|
(3)
|
|
|
ns_name:: name
|
(4)
|
|
|
using namespace ns_name;
|
(5)
|
|
|
using ns_name:: name;
|
(6)
|
|
|
1) Declaration of the namespace ns_name.
2) Declaration of the namespace ns_name. Definitions will appear both inside ns_name and its enclosing namespace.
3) Unnamed namespace. Definitions have potential scope from their point of declaration to the end of the translation unit, and have
internal linkage.
4) Namespace names (along with class names) can appear on the left hand side of the scope resolution operator, as part of
qualified name lookup.
5) using-directive: makes all symbols of the namespace
ns_name accessible for
unqualified lookup as if declared in the nearest enclosing namespace which contains (directly or indirectly) both the using-directive and the namespace
ns_name.
6) using-declaration: makes the symbol
name
from the namespace
ns_name accessible for
unqualified lookup as if declared in the same namespace as where this using-declaration appears.
[edit] Explanation
[edit] Namespaces
[edit] The unnamed namespace
[edit] Inline namespaces
[edit] Using-declarations
[edit] Using-directives
The using-directive using namespace std;
at any namespace scope introduces every name from the namespace std
into the global namespace (since the global namespace is the nearest namespace that contains both std
and any user-declared namespace), which may lead to undesirable name collisions. This, and other using directives are generally considered bad practice at file scope of a header file.
[edit] Example
This example shows how to use a namespace to create a class that already has been named in the std
namespace.
#include <vector>
namespace vec {
template< typename T >
class vector {
// ...
};
} // of vec
int main()
{
std::vector<int> v1; // Standard vector.
vec::vector<int> v2; // User defined vector.
v1 = v2; // Error: v1 and v2 are different object's type.
{
using namespace std;
vector<int> v3; // Same as std::vector
v1 = v3; // OK
}
{
using vec::vector;
vector<int> v4; // Same as vec::vector
v2 = v4; // OK
}
return 0;
}
[edit] See also