Search code examples
c++namespacesusingusing-directives

Is it recommended to use the using keyword in a function?


I'm editing a large source file that was authored by someone else. They didn't put the using namespace xxx directive in file scope and I don't want to add it at file scope and edit all occurrences of xxx::typename to typename. But, at the same time, I don't want to keep typing all these long nested namespace names in a new function that I'm writing in this file, so I decided to use the using directive inside the function like so:

void foo()
{
  using namspace namesp1::namesp2;

  // do foo stuff
}

This code compiles fine, but I'm not sure if there are any gotchas. Are there any rules that dictate when file or function scope should be preferred?


Solution

  • There are gotchas with it as such. Whatever the problem exists if you put using namespace blah; at file scope, still exists but is limited to just the function. It's generally a reasonable compromise when you had to type very long type names (foo::bar::blah::something::thingy var;).

    A slightly better option is to use an alias:

    void foo()
    {
        using p1p2 = namesp1::namesp2;
    
        // do stuff
    }
    

    Then you can use p1p2::thingy which makes namespace collisions even less likely.