C++ using for std and boost namespace best practice

Issue

Possible Duplicate:
Do you prefer explicit namespaces or ‘using’ in C++?

I am a C# developer, but my friend is a C++ one. He has shown me the code which is filled with calls like std::for_each and boost::bind. I used in C# and thought that using directives would rock for readability of the code and generally faster development. It would be a pain in the neck to type any namespace before C# foreach statement for example.

What are the cons and pros of using for such popular namespaces I am wondering?

Is it a best practice to include those namespaces or not?

Solution

First of all, let’s make two distinctions:

1) There are using directives like using namespace std; and using declarations like using std::cout;

2) You can put using directives and declarations in either a header (.h) or an implementation file (.cpp)

Furthermore, using directives and declarations bring names into the namespace in which they’re written, i.e.

namespace blah
{
    using namespace std; // doesn't pollute the *global* namespace, only blah
}

Now, in terms of best practice, it’s clear that putting using directives and declarations in a header file in the global namespace is a horrible no-no. People will hate you for it, because any file that includes that header will have its global namespace polluted.

Putting using directives and declarations in implementation files is somewhat more acceptable, although it may or may not make the code less clear. In general, you should prefer using declarations to using directives in such instances. My own preference is to always specify the namespace, unless it’s annoyingly long (then I might be tempted).

In a header, if typing the namespace every single time is getting really tedious, you can always introduce a “local” namespace, e.g.

namespace MyLocalName
{
    using namespace boost;

    class X
    {
        // can use things from boost:: here without qualification
    };
}

using MyLocalName::X; // brings X back into the global namespace

But never put using namespace boost; or the equivalent somewhere where it will drag all the stuff from Boost into the global namespace itself for other people.

Answered By – Stuart Golodetz

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.