I've had a small taste of namespace usage in C++ with the std library. I know there are some differences, but it seems C++ namespaces could be used in much the same way Java packages are used. Do people do this in C++? I haven't attempted this myself, and I haven't seen an explicit example of nested namespaces, but I have seen the scope resolution operator used twice, e.g., top::outer::inner when resolving class methods in multiple inheritance situations. Such an approach seems to work fairly well in Java. Are there reasons to use or avoid such a namespace structure in C++? Assuming it can even be done. STH
Steven T. Hatton wrote:
I've had a small taste of namespace usage in C++ with the std library. I know there are some differences, but it seems C++ namespaces could be used in much the same way Java packages are used. Do people do this in C++?
Yes. I had an older version of gcc on solaris that didn't handle namespaces well, but otherwise they work fine. Often, you can use the Java-style alternative: class name { private: A(){} public: static int f( int x ); //... }; Namespaces have some advantages if you just want a collection of functions: they are open and you have the using directive that allows you to add to an existing library or select from an existing library at will.
I haven't attempted this myself, and I haven't seen an explicit example of nested namespaces, but I have seen the scope resolution operator used twice, e.g., top::outer::inner when resolving class methods in multiple inheritance situations.
Such an approach seems to work fairly well in Java. Are there reasons to use or avoid such a namespace structure in C++? Assuming it can even be done.
Use it as and when it's useful. Often, you would use the using directive to simplify the appearance. For example, if you have a complex namespace structure, you might use namespace my_maths { using maths::random::normal; using maths::trigonometry::cosine; } -- JDL Non enim propter gloriam, diuicias aut honores pugnamus set propter libertatem solummodo quam Nemo bonus nisi simul cum vita amittit.
participants (2)
-
John Lamb
-
Steven T. Hatton