Declaring using statement after namespace declaration

268 views Asked by At

I am writing a utility library which is made up of several "Packages". The classes in each package are contained in various namespaces. I have an idea as to how I can simplify the situation by automatically declaring using statements at the end of class declarations (see below), this will avoid having the programmer do it in a cpp file.

namespace Utility
{
    class String
    {
        // Class Implementation
    };
}

using Utility::String;

My understanding is that if the user includes the header String.h and String is in Utility then the programmer will want to use String. Obviously this could be bad if there are outside classes chain including a bunch of files which dirty up the namespace so I thought how about making it a #define instead.

namespace Utility
{
    class String
    {
        // Class Implementation
    };
}

#ifdef AUTO_DECLARE_NAMESPACE
    using Utility::String;
#endif

That way, programmers that want this extended functionality can get it.

Would this a good idea or is there something I'm overlooking?

4

There are 4 answers

0
James McNellis On BEST ANSWER

There is no point in using namespaces if you are just going to add a using declaration for each and every name declared in the namespace.

Let users of your header files decide how they want to use the headers. If someone wants to use a using declaration, let him do it in the .cpp file directly; this will make the code in that .cpp file clearer since it will be apparent where the name originated.

0
Sion Sheevok On

Honestly, I believe that's what the using namespace directive is for. There's no need for you to add this preprocessor mechanism, considering the using namespace directive does just that.

0
James McLeod On

This seems at best pointless, and at worst annoying.

What is wrong with having developers decide which namespaces to use and what to qualify fully?

0
n1ckp On

Couldn't you have another .h file with all your usings like my_lib_import_names.h and just #include that to get what you want?

You would probably have problem with classes not being declared but you could probably bypass it by using something like:

#ifdef UTILITY_STRING_H_ 
  using Utility::String;
#endif
..
#ifdef UTILITY_SOMETHING_ELSE_H
   using Utility::SomethingElse;
#endif

..

What do you think?

That way you could retain the "expected" behavior in your library .h but also have your the way you like. You also get to keep the benefit of the namespace over your classes (at the expense of having to maintain your new .h file).