Trevor Hickey
Trevor Hickey

Reputation: 37806

How do I get code to exist in the scope of two or more non-nested namespaces?

I would like an object/function to only be in the current scope when all of the necessary namespaces are being used.

For example, let's say there is an H2O(water) object.
It relies on both the hydrogen namespace and the oxygen namespace in order to be created and used.

Since water relies on both of these namespaces, here is the behaviour I would like:

int main(){

    using namespace oxygen;
    using namespace hydrogen;
    H2O water; //<- Works. In scope.
}


int main(){

    //using namespace oxygen;
    using namespace hydrogen;
    H2O water; //<- NOT IN SCOPE
}

int main(){

    using namespace oxygen;
    //using namespace hydrogen;
    H2O water; //<- NOT IN SCOPE
}

int main(){

    //using namespace oxygen;
    //using namespace hydrogen;
    H2O water; //<- NOT IN SCOPE
}

Is this possible? If not, what alternatives are best recommended?

Upvotes: 1

Views: 57

Answers (2)

Corbin
Corbin

Reputation: 33437

This is not possible.

I can't see where there would be much use for this. The idea that immediately comes to mind though is to have a Molecule that contains Atoms (or whatever the correct chemical terminology is -- it's been a while) and only export the Oxygen Atom in the oxygen namespace, and the hydrogen in its respective namespace. That would mean that a water molecule could only be constructed when both oxygen and hydrogen were visible.


I'm still a bit skeptical if this is the right approach though. Namespaces are used for organisation. Hiding otherwise public types doesn't particularly make sense.

Upvotes: 2

Alan Stokes
Alan Stokes

Reputation: 18964

No. (Fundamentally, you don't get to decide how other developers choose to reference the symbols you declare.)

Upvotes: 2

Related Questions