Yamahari
Yamahari

Reputation: 2038

C++ "Using" in Modules

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";
}

Upvotes: 9

Views: 1249

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473272

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.

Upvotes: 3

Related Questions