Skip to content

Design note: Namespaces

Herb Sutter edited this page Nov 26, 2022 · 4 revisions

Q: Should namespaces be their own standalone feature, as in Cpp1?

A: Maybe, but I'm going to see if we can do better using metaclass functions and partial types.

I intend to initially implement namespace as a standalone feature, as it is in today's syntax, just so that there's something to use short-term even before I add support for classes.

But I'm curious whether a namespace metaclass function will work. The idea is that, like interface and base_class and value and such are specializations of the general type, perhaps namespace could be expressed like that as well. One benefit I hope this might bring to users would be able to naturally use type features, notably that private access could be a nice replacement for the ::detail subnamespace idiom. See P0707 section 3.11 for a discussion. There are other potential smaller simplification benefits.

However, the main difference between a namespace and those other kinds of restricted types like interface and value is that a namespace can be reopened. So to make it possible to express a namespace as a restricted type would require that types themselves support partial types that can be reopened. But that's interesting because, as shown on that C# doc page, partial types are a generally useful feature, not something I'd add only to be able to use them to express namespaces. For example, partial types are known to be useful for frameworks that rely on source generation to produce part of the code for a type, by allowing such generated code to be emitted as a self-contained unit that's a partial type, rather than as a brittle and easily-disturbed chunk of generated code inside the main manually-written type, usually with comments like "please don't change any of the code inside these comments!!" around it... experience has found these are error-prone in practice, and when the programmer disturbs code inside the comments (or even near the comments) it's easy to confuse the code generator so that they can't update the code, or can't round-trip the code.

We'll see how it goes!