C++ · 1 · Foundations3 / 36 · 8%
Namespaces & Organisation
Avoid name collisions without prefixing every symbol.
Examples: namespace, ::, using, anonymous namespace
shortcuts: ← prev · → next · M mark
1
Declaring a Namespace
Group related names under a scope.
Example
example
namespace app::net {
class Socket { /* ... */ };
void connect(Socket&);
}
app::net::Socket s;
namespace net = app::net; // alias
net::connect(s);2
using — Carefully
using namespace std; in a header poisons every file that includes it.
Example
example
using std::string; // fine: one specific name
using namespace std; // avoid in headers, tolerable in a .cpp
// std::count vs a local count() becomes ambiguousWATCH OUT
Never put `using namespace` at file scope in a header.
3
Anonymous Namespace
The C++ replacement for file-scope static.
Example
example
namespace {
int helper_counter = 0; // internal linkage
void helper() { /* ... */ }
}4
ADL
Argument-dependent lookup finds functions in the namespace of the argument type.
Example
example
namespace geo { struct Point{int x,y;}; void print(const Point&); }
geo::Point p;
print(p); // found via ADL — no geo:: needed