Effective C++ Note 28: Use of namespace
Name conflicts have long been a pain for C programers. When you try to include two header files which happen to have the name conflicts, it can really make your day an unpleasant one. Fortunately, C++ provides namespace, which is a cure to name conflicts.
Without namespace, you may write code like this:
const double sdmBOOK_VERSION = 2.0; // in this library,
// each symbol begins
class sdmHandle { ... }; // with "sdm"
sdmHandle& sdmGetHandle(); // see Item 47 for why you
// might want to declare
// a function like this
while you may have it like this if you use namespace:
namespace sdm {
const double BOOK_VERSION = 2.0;
class Handle { ... };
Handle& getHandle();
}
Here is how we use namespace:
void f1()
{
using namespace sdm; // make all symbols in sdm
// available w/o qualification
// in this scope
cout << BOOK_VERSION; // okay, resolves to
// sdm::BOOK_VERSION
...
Handle h = getHandle(); // okay, Handle resolves to
// sdm::Handle, getHandle
... // resolves to sdm::getHandle
}
void f2()
{
using sdm::BOOK_VERSION; // make only BOOK_VERSION
// available w/o qualification
// in this scope
cout << BOOK_VERSION; // okay, resolves to
// sdm::BOOK_VERSION
...
Handle h = getHandle(); // error! neither Handle
// nor getHandle were
... // imported into this scope
}
void f3()
{
cout << sdm::BOOK_VERSION; // okay, makes BOOK_VERSION
// available for this one use
... // only
double d = BOOK_VERSION; // error! BOOK_VERSION is
// not in scope
Handle h = getHandle(); // error! neither Handle
// nor getHandle were
... // imported into this scope
}