D has a fantastic module system which reduces compilation times dramatically compared to C++. According to the documentation D still provides opaque structs and unions in order to enable the pimpl idiom. My question is: How can I declare a nested struct (or union) in one module and define it in another one? What is the syntax for that?
In C++ the header would look like this
struct S {
...
struct Impl;
Impl * p;
};
and the implementation file (cpp-file) would use some interesting-looking ::-syntax like this:
#include "header.h"
struct S::Impl {
...
};
How do I implement the same in D?
D (DMD, at least) uses
.difiles for declarations. They are somewhat equivalent to C.hfiles, however they are optional. The D compiler can generate.difiles automatically (when the-Hswitch is specified), although I believe that currently all it does is strip function bodies and unittests.Here's one way to achieve PImpl using
.difiles:mod.di:mod.d:Note that it is currently your responsibility to make sure that the fields in
Sare the same in both the.dand.difile - if they differ, the compiled modules will have differing knowledge of how the fields are laid out, which can lead to memory corruption. The current compiler implementations do not verify if definitions match in.dand.difiles.