0

In C++ Primer, there is one tips says:

One place where using directives are useful is in the implementation files for the namespace itself.

I guess this is just for using shorthand names? I am not sure how it is different from just surrounding the implementation with

namespace namespace_name
{
}

Thanks.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
Sean
  • 2,649
  • 3
  • 21
  • 27

2 Answers2

1

That applies to modifications to your own namespaces. The purpose of using directives is to import symbols from a different namespace. For example, an infamous idiom:

namespace my_stuff
{
  template <typename Container>
  void my_fn( Container& xs )
  {
    using std::begin;
    using std::end;
    std::sort( begin(xs), end(xs) );
  }
}

Everything happens in your my_namespace, but it makes available the std::begin() and std::end() functions if needed. If a more local definition for begin() and end() exists that better matches the Container type, then it will be used instead. If you had simply wrapped everything in the std namespace, this useful ability would be lost.

Hope this helps.

DĂșthomhas
  • 8,200
  • 2
  • 17
  • 39
1

I am not sure how it is different from just surrounding the implementation with namespace namespace_name { }

This is to put your own code within a namespace, as opposed to using some name from another namespace. Say you write a draw function inside the Graphics namespace -- to do this, you wrap draw's code in namespace Math { void draw() { /* some code */ } } and to use it you'd do Graphics::draw. However, when you need to use a function, say, gamma in the Math namespace (which you didn't write), you've to call it Math::gamma for the compiler to know where to search for gamma. Alternatively, you may use shorthand, to drop the Math:: part.

I guess this is just for using shorthand names?

Yes, that's to allow identifiers from some namespace to be used without the qualifier. There are two ways to do it.

  1. Using directive: Use all names in a namespace without qualification (e.g. using namespace Math;)
  2. Using declaration: Use only some specified names without qualification (e.g. using Math::gamma) -- this is usually better than the former.

However, both are encouraged to be used only in an implementation/source file and not in a header to avoid some sources which may have its own copy of gamma and don't want to use Math::gamma, but since you've it in the header, it'll lead a clash of the names. More details on "using namespace" in c++ headers.

Community
  • 1
  • 1
legends2k
  • 31,634
  • 25
  • 118
  • 222