Maddy's Rant

Vacuous, vivid, vivacious, aphrodisiac, simulating, rapid, ravenous

Name:
Location: Bellevue, WA, United States

Come and sit with me my friend, I promise to show you the world beyond your wildest imagination.

Wednesday, July 06, 2005

C++ ramblings

Using Namespaces

There are four ways you can refer to namespace members:

  • Using the full member name, including the namespace it belongs to. For example:

    std::cout << "Hello Nasty";
    Note: Remember that on Pre-Draft days, cout was not declared in any namespace (they didn't exist yet, anyway), and header files used an .h suffix.
  • By taking advantage of Using-Declarations, as in

    using std::cout;
    cout << "Hello Nasty";
    this declares cout in the current scope as synonym for std::cout.
  • By taking advantage of Using-Directives, as in

    using namespace std;
    cout << "Hello Nasty";
    which specifies that the current scope can refer to names in the std namespace without using full qualifiers. This is mostly used when porting legacy code.
  • Using aliases. Say, for example, I have

    namespace X
    {
    namespace Y
    {
    class Z { ... };
    }
    }
    The full qualifier for Z is X::Y::Z, but we can declare an alias using

    namespace w = X::Y;
    This declares w as an alias for namespace X::Y, thus we can access Z using w::Z.
    Note: As you can see, namespaces can be nested. One of the design goals of namespaces was to encourage programmers and vendors to wrap their libraries inside them, minimizing name collisions. One particularly useful way of taking advantage of this is when you are designing libraries for, say, your company, which involve several pieces of functionality. For example, I keep some of my reusable system classes and templates in a WRuntime namespace, which contains different namespaces inside it like WThreading and WLogging.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home