r/cpp_questions • u/Equivalent_Union2768 • 9d ago
OPEN cpp class vs namespace
in my personal opinion, at least half of the purpose of using nested namespace is to manage visibility, the rust's mod allows it but cpp's namespace does not, only class allows it( the public and private)
is using classes with static functions inside everywhere instead of using namespace an already existing way to use the "namespace" in a way that i can more conveniently manage visibility?
3
Upvotes
View all comments
7
u/IyeOnline 9d ago
What you are describing is not visibility. Private members are visible, they are just not accessible. C++ namespaces are concerned with name resolution (which actually is tied to visibility).
In a sense this is a missing feature, but its also a somewhat niche problem.
You can use classes-as-namespaces in order to control access, but it is rather uncommon.
More commonly you would open up some nested
detail(or_,internal, ...) namespace, communicating that external consumers should not use those identifiers. Sure, they can still do it then, but you can just declare its their fault if anything breaks.Ideally, you just dont put things you dont want other to use into a header they can include.
With C++20 modules, you have other options as well: A module allows you to explicitly
exportonly the entities you want usable outside of your module. If you can use modules, that is what I would suggest.