Using directive

suggest change

The keyword ‘using’ has three flavors. Combined with keyword ‘namespace’ you write a ‘using directive’:

If you don’t want to write Foo:: in front of every stuff in the namespace Foo, you can use using namespace Foo; to import every single thing out of Foo.

namespace Foo
{
    void bar() {}
    void baz() {}
}

//Have to use Foo::bar()
Foo::bar();

//Import Foo
using namespace Foo;
bar(); //OK
baz(); //OK

It is also possible to import selected entities in a namespace rather than the whole namespace:

using Foo::bar;
bar(); //OK, was specifically imported
baz(); // Not OK, was not imported

A word of caution: using namespaces in header files is seen as bad style in most cases. If this is done, the namespace is imported in every file that includes the header. Since there is no way of “un-using” a namespace, this can lead to namespace pollution (more or unexpected symbols in the global namespace) or, worse, conflicts. See this example for an illustration of the problem:

/***** foo.h *****/
namespace Foo
{
    class C;
}

/***** bar.h *****/
namespace Bar
{
    class C;
}

/***** baz.h *****/
#include "foo.h"
using namespace Foo;

/***** main.cpp *****/
#include "bar.h"
#include "baz.h"

using namespace Bar;
C c; // error: Ambiguity between Bar::C and Foo::C

A using-directive cannot occur at class scope.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Namespaces:
* Using directive

Table Of Contents
8 Arrays
11 Loops
39 Streams
51 Unions
53 Namespaces
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype