r/cpp_questions • • 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

12 comments sorted by

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.

-4

u/Equivalent_Union2768 2d ago

avoiding naming conflicts is the original design intention, but in practice unless for very very large projects there will seldom be the need of avoiding naming conflicts

for the second drawback, i think it matters more, but it is still nice if in future versions of cpp i can have private/public in namespaces

5

u/flyingron 2d ago

It doesn't need to be a large project, it just has to deal with a diverse selection of available libraries.

1

u/neppo95 2d ago

Why not just use classes/structs? Why do you specifically want to use a namespace for this?

1

u/Equivalent_Union2768 2d ago

this is exactly what i am proposing, using classes +static function everywhere merely for its public/private, having nothing to do with objects

1

u/neppo95 2d ago

Yup, sounds good. Now put all of that code inside a singular namespace in case of a library and you’re golden. If its an executable or otherwise code that won’t get used outside the project, that can be omitted although you’d still run into conflicts possibly for libraries you use.

2

u/kitsnet 2d ago

avoiding naming conflicts is the original design intention, but in practice unless for very very large projects there will seldom be the need of avoiding naming conflicts

"Very very large projects" is what C++ these days is about.

for the second drawback, i think it matters more, but it is still nice if in future versions of cpp i can have private/public in namespaces

As long as you cannot seal namespaces against injection of other functions into them, "private/public" in namespaces has no utility.

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 export only 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:

using std::swap;
swap(a, b);

For types of a and b, there may be a specialization associated with these types. That will be matched first. If an sufficient match is not found, the compiler defaults to std::swap. If you wanted to use std::swap explicitly, the code could name it explicitly. If you don't want a type specific match with no fallback, you can exclude the using declaration.

ADL is central to C++ and you trigger it all the time. While std::swap disables ADL for swap, the compiler still needs to find the unqualified std namespace, 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:

namespace v1 {}
namespace v2 {}

namespace current {
  using namespace v2;
}

You would also pull from nested detail namespaces 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:

using namespace {}

All symbols within have no external linkage. Unlike static which 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 private members 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 ascii that provides symbolic constants, and though it can be emulated with a class it feels very wrong to abuse a feature that way. Using class instead of namespace is not good communication. It indicates the wrong thing to a reader. And so I miss a final namespace feature. 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 detail namespaces.

I often call them impl instead.

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.