10

One of the reasons "using namespace" in header files is considered bad practise (Why is "using namespace std;" considered bad practice?) is because it "leaks" the using-directive to everyone that includes your headerfile. Is this still the case for C++ modules or can I "safely" put e.g. using namespace std or using std::cout into my module? :

module;
#include <iostream>
export module Module;

using namespace std;
// using std::cout;
export void greet() {
    cout << "Hello World!\n";
}
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
Yamahari
  • 1,926
  • 9
  • 25
  • FWIW, another reason not to use `using namespace std;` is that it can cause problems in the header itself. For something as short as adding `std::` to a standard library usage, it's still not worth using `using namespace std;`. – NathanOliver Oct 27 '20 at 16:00
  • @NathanOliver `that it can cause problems in the header itself`, that reason would not be limited to headers but should be true for cpp files? – t.niese Oct 27 '20 at 18:10
  • @t.niese It's true for all files. `using namespace std;` likes to break all sorts of things. – NathanOliver Oct 27 '20 at 18:15

1 Answers1

4

The scope of any using declaration of this sort is the translation unit being compiled. All module files (a file that starts with some form of module declaration) is a separate translation unit. So it will be just like any other non-exported declaration in your module: local to it.

That having been said, this is only one reason to avoid using namespace std; there are many others. It can play havoc with name lookup. The included names can clash with global names and names used in your namespace. And so forth.

However, employing using declarations for specific components of the std namespace is a lot more reasonable, as the primary reason not to do so is to prevent leakage. Also, namespace aliases are a good idea too, for sub-namespaces like std::chrono, std::filesystem, and the like.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • 3
    Note that, unlike *using-declaration*s, you can’t export *using-directive*s in (the published) C++20 (although it’s conceivable that that could be considered a defect after the fact), except by having them in a header unit (where everything is). – Davis Herring Oct 28 '20 at 03:35