Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using a local clone.

Add namespace scopes to support referencing external C++ symbols in C++ namespaces

Version 1
Created 2014-04-26
StatusImplemented
Last modified 2014-04-26
Author Walter Bright

Abstract

Add ability to reference from D C++ symbols that are in C++ namespaces.

Rationale

Best practices in C++ code increasingly means putting functions and declarations in namespaces. Currently, there is no support in D to call C++ functions in namespaces. The primary issue is that the name mangling doesn’t match. Need a simple and straightforward method of indicating namespaces.

Description

A namespace scope creates a scope with a name, and inside that scope all declarations become part of the namespace scope. This involves the addition of a small amount of new grammar. Compiler changes are expected to be minor. The change is additive and should not impact any existing code.

The namespace is identified by an identifier following the C++ in extern(C++). Nested namespaces can be specified using . to separate them.

Usage

extern (C++, MyNamespace) { int foo(); }

creates a namespace named “MyNamespace”. As is currently the case,

extern (C++) { int foo(); }

does not create a namespace.

The following declarations are all equivalent:

extern (C++) { extern (C++, N) { extern (C++, M) { int foo(); }}}
extern (C++, N.M) { int foo(); }
extern (C++, N) { extern (C++) { extern (C++, M) { int foo(); }}}

Namespaces can be nested. Declarations in the namespace can be accessed without qualification in the enclosing scope if there is no ambiguity. Ambiguity issues can be resolved by adding the namespace qualifier:

extern (C++, N) { int foo(); int bar(); }
extern (C++, M) { long foo(); }

bar(); // ok
foo(); // error, ambiguous
N.foo(); // ok
N.bar(); // ok

Name lookup rules are the same as for mixin templates.

Unlike C++, namespaces in D will be ‘closed’ meaning that new declarations cannot be inserted into a namespace after the closing }. C++ Argument Dependent Lookup (aka “Koenig Lookup”) will not be supported.

Grammar Change

LinkageAttribute:     extern ( identifier )\     extern ( identifier ++ )\     extern ( identifier ++ , identifier ( . identifier )* )

This document has been placed in the Public Domain.