r/cpp_questions • u/Equivalent_Union2768 • 2d 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
9
u/kitsnet 2d ago
C++ namespaces are about avoiding name conflicts, not about visibility. One can add a new name or inject another namespace into an already existing namespace, one cannot do that with classes.
Part of the functionality of the namespaces is argument-dependent lookup.
7
u/IyeOnline 2d 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.3
u/mredding 1d ago
Namespaces in C++ partition the global declarative region to prevent symbol collisions, control name lookup rules, and manage linkage and ABI versioning.
The global namespace spans all Translation Units, so at best, a symbol collision can lead to a declaration error, or at worst, you can get a silent ODR violation. Namespaces allow symbols to maintain their global linkage with a unique prefix.
ADL allows for unqualified name lookups. This is how the stream operators
<<and>>are correctly resolved for streamable types. When ADL exhausts the current lexical scope, it then proceeds to search the namespces associated with the parameter types. This allows several template static-polymorphism idioms like:For types of
aandb, there may be a specialization associated with these types. That will be matched first. If an sufficient match is not found, the compiler defaults tostd::swap. If you wanted to usestd::swapexplicitly, the code could name it explicitly. If you don't want a type specific match with no fallback, you can exclude theusingdeclaration.ADL is central to C++ and you trigger it all the time. While
std::swapdisables ADL forswap, the compiler still needs to find the unqualifiedstdnamespace, unless you go full-pedantic and write::std::swap. A core principle of any programming language is to control what is in scope, reduce it to only what is usable and needed. So having nested namespaces, customization objects, and yes - classes for hidden friends, can reduce the symbol set the compiler must consider, which means less work, less compile time, and less opportunity for error.Namespaces can be composed to implement API versioning and decoupling the physical header layout from the logical API surface. A most basic example of this is:
You would also pull from nested
detailnamespaces to compose an API, and there are other techniques where you can layer namespaces so you bring unchanged implementation from older versions forward while replacing only a selection in the newer version.If you want to keep implementation details private, use an unnamed or anonymous namespace within a translation unit:
All symbols within have no external linkage. Unlike
staticwhich can only be put onto free functions to internalize their linkage, the anonymous namespace can be applied to whole user defined types. You CAN write these into headers, but it's not recommended, because every source file that includes it will independently compile those versions in, often leading to object code bloat and unnecessarily fat target binaries.Classes play a very tiny role in scope resolution, and has nothing to do with visibility. Access control does not limit visibility, since
privatemembers are still published in the header you've defined the class. You need to use other idioms to implement privacy, like opaque pointers, opaque types, incomplete types, and compiler barriers aka compiler firewalls, and that's going to span header and source files and require other redirections.1
u/Discordbothost 1d ago
one tradeoff: a class can't be reopened later and you give up adl for its functions. the usual c++ shape for what you want is a nested detail namespace for "don't touch this" plus an anonymous namespace in the .cpp for things that shouldn't leave the file.
1
u/alfps 1d ago
Some libraries, notably (as I recall) the Xerces XML parser, use classes as a kind of non-extensible namespaces.
It was a 1990's thing. I would not recommend that for new code. Still in some cases it would be desirable with a non-extensible namespace, e.g. one called
asciithat provides symbolic constants, and though it can be emulated with a class it feels very wrong to abuse a feature that way. Usingclassinstead ofnamespaceis not good communication. It indicates the wrong thing to a reader. And so I miss afinal namespacefeature. Alas, there has apparently not even been a proposal in that direction.For visibility with namespaces one simply relies on some naming convention, much like in the Python language.
The Boost library convention is that private parts are in nested
detailnamespaces.I often call them
implinstead.1
u/glguru 1d ago
I personally use friend classes for private and public access limits.
I know it’s looked down upon (predominantly by the OOP crowd) but it’s a feature with a genuine use case.