Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "using" keyword in C++

Tags:

c++

I am little confused as to which one is the better way to use using C++ keyword for namespaces. Suppose that the following code is in a header file backtrace.h

#include <memory>
using my_namespace1::component1;
using my_namespace2::component2;
namespace my_application {
  namespace platform_logs {
    class backtrace_log {
          //code that creates instances of my_namespace1::component1 and my_namespace2::component2
    };
  }
}

OR

#include <memory>    
namespace my_application {
  namespace platform_logs {
    using my_namespace1::component1;
    using my_namespace2::component2;

    class backtrace_log {
          //code that creates instances of my_namespace1::component1 and my_namespace2::component2
    };
  }
}

which one is better and why ?

like image 342
Monku Avatar asked May 25 '17 17:05

Monku


2 Answers

You should always pull in symbols from other namespaces in as narrow a scope as possible (to not pollute outer namespaces) and generally, only pull in the specific symbols you need, not just the entire namespace.

In headers (that may get included by many users) you should generally refrain from the practice alltogether and instead prefer to always just use explicit namespace qualifications on types.

like image 137
Jesper Juhl Avatar answered Oct 05 '22 12:10

Jesper Juhl


In a header file... the following example is evil. Never use using namespace... in the global scope of a header file. It forces a lot of unasked for symbols on the user that can cause very hard to fix problems if they clash with other headers.

#include <memory>
using my_namespace1::component1;
using my_namespace2::component2;
namespace my_application {
  namespace platform_logs {
    class backtrace_log {
          //code that creates instances of my_namespace1::component1 and my_namespace2::component2
    };
  }
}

On the other hand this next example is fine, but to be used with caution. It only makes sense if you want to include all those symbols in your API. This is often the case with internal project name spaces but less likely with third party namespaces.

I would especially avoid even this with very large namespaces like std::.

#include <memory>    
namespace my_application {
  namespace platform_logs {
    using my_namespace1::component1;
    using my_namespace2::component2;

    class backtrace_log {
          //code that creates instances of my_namespace1::component1 and my_namespace2::component2
    };
  }
}
like image 28
Galik Avatar answered Oct 05 '22 11:10

Galik