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: 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.
std::cout << "Hello Nasty";
- By taking advantage of Using-Declarations, as in this declares cout in the current scope as synonym for
using std::cout;
cout << "Hello Nasty";
std::cout
. - By taking advantage of Using-Directives, as in which specifies that the current scope can refer to names in the
using namespace std;
cout << "Hello Nasty";
std
namespace without using full qualifiers. This is mostly used when porting legacy code. - Using aliases. Say, for example, I have The full qualifier for Z is
namespace X
{
namespace Y
{
class Z { ... };
}
}
X::Y::Z
, but we can declare an alias usingThis declares w as an alias for namespace X::Y, thus we can access Z using
namespace w = X::Y;
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 aWRuntime
namespace, which contains different namespaces inside it likeWThreading
andWLogging
.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home