Monday, April 27, 2009

Making C++ do C99 things (part 1/3)

C99 (the 1999 ISO revision of the ANSI C standard) was extended to allow a special syntax for initializing structures: designated initializers. This allows the initialization of a possibly-complicated structure using the names of the individual entries. For example,
XSetWindowAttributes xswa = {
‍ ‍ .bit_gravity = ForgetGravity,
‍ ‍ .background_pixmap = None
};
is a legal way of setting only the named members of the structure. (The remainder of the structure members will be default-initialized.)

Designated initializers have not been approved for C++0x, and seem unlikely to be, due to lack of time and consideration. This is fair, really; in C++ one could simply write an immediate local subclass—
struct xswa_t : XSetWindowAttributes {
‍ ‍ xswa_t() : bit_gravity(ForgetGravity), background_pixmap(None) {}
‍ ‍ XSetWindowAttributes &POD() { return this; }
‍} xswa;
which would effectively function exactly as the designated-initializer version does, right down to &xswa being a legal argument to XChangeWindowAttributes(). (It wouldn't quite be POD, because it doesn't have a trivial default constructor; this might matter if you had to pass it into a metaprogrammatic POD-aware template function, so the POD() method has been outlined above, as a shorthand for (XSetWindowAttributes&).)

But that's just too easy; so next time I'll describe how to make the following syntax work.
XSetWindowAttributes_ xswa = {
‍ ‍ bit_gravity_ = ForgetGravity,
‍ ‍ background_pixmap_ = None
};


Edit 2009-04-28: Fixed minor verbiage error and minor syntax error.

No comments: