如何在C++中使用"using"关键字

Mon*_*nku 6 c++

我很困惑哪一个是使用usingC++关键字命名空间的更好方法.假设以下代码位于头文件中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
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

要么

#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
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

哪个更好,为什么?

Jes*_*uhl 8

您应该始终在尽可能狭窄的范围内从其他命名空间中提取符号(以便不污染外部命名空间),并且通常只提取您需要特定符号,而不仅仅是整个命名空间.

标题中(可能被许多用户包括在内),您通常应该完全避免这种做法,而是更喜欢始终只对类型使用显式名称空间限定.


Gal*_*lik 5

在头文件中,以下示例是邪恶的。切勿using namespace...在头文件的全局范围内使用。如果用户与其他标头发生冲突,这会迫使用户对符号进行大量索取,从而导致很难解决的问题。

#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
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

另一方面,下一个示例很好,但请谨慎使用。如果你把它才有意义,以包括所有这些符号 API内部项目名称空间通常是这种情况,但第三方名称空间的可能性较小。

我尤其会避免使用大型命名空间(例如)来避免这种情况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
    };
  }
}
Run Code Online (Sandbox Code Playgroud)