frozenca
frozenca

Reputation: 877

C++ resolving using namespace std problems using modules

As we know, using using namespace std; in header files is banned in all nontrivial projects. I hate this verbosity but understand its rationale behind.

However, I'm wondering if using C++20/23 modules could be a solution to this.

AFAIK declaring using namespace std; in global scope of headers has two biggest problems:

  1. It pollutes the namespace of all users who include the header.

  2. It pollutes the namespace of all identifiers within the header.

Personally I don't think the second problem is that severe, because the affected scope of identifiers is restricted within a single translation unit. So as far as I know the main reason why people are frowned upon is the first one.

And it seems to me that modules can solve the first one, like this:

export module frozenca;

import std.compat;

// ↓ I think this is definitely NOT OK
// export using namespace std;

// I think this is OK as this is not "propagated" outside of the module.
// Am I correct?
using namespace std; 

// .. other details ..

I couldn't find any implementation that the code above compiles, so I couldn't test. Am I correct?

Upvotes: 1

Views: 183

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473926

For the factual form of your question, you are correct. using directives declared in a module unit don't get exported to the interface of that unit. Therefore, they and their effects are locally contained within the module TU which declares them. An import will not using namespace anything.

And for what it's worth, you cannot export using namespace at all. That's a compile error.


That having been said, you should be aware that std contains a lot of names. Many of those names are short, single-word names like begin or sort and the like. Names that you might want to use yourself in certain places.

By bringing in the entirety of std into the local scope, you're opening yourself up to all kinds of potential conflicts.

std:: is just five characters. Get used to them.

Upvotes: 2

Related Questions