Pretty please: Named arguments

Jonathan M Davis jmdavisProg at gmx.com
Sun Mar 6 17:29:58 PST 2011


On Sunday 06 March 2011 16:57:17 Joel C. Salomon wrote:
> (De-lurking; I've been interested in D for a while, but my programming
> is almost exclusively in C -- generally C99.)
> 
> Does D have the equivalent of C99's "designated initializers"?
> 
> Were I to attempt something like this in C, the code would go something
> like this:
> 
>     int foo(int height, int width);
>     struct _foo_args {
>         int height; int width;
>     };
>     #define foo(...) \
>         foo((struct _foo_args){__VA_ARGS__}.height, \
>             (struct _foo_args){__VA_ARGS__}.width)
> 
> at which point each of these calls:
> 
>     foo(a, b);
>     foo(.height = a, .width = b);
>     foo(.width = b, .height = a);
> 
> have the same effect.
> 
> I'll readily admit this is *not* pretty, and likely more effort than
> it's worth, but is will work.
> 
> Are D's compile-time operations not capable of something at *least* this
> powerful?

D doesn't have macros. It has incredibly powerful templates as well as string 
mixins, but no macros. So, what D has tends to be very powerful, but there are 
times when it's more verbose to use than a C macro might be, and there are some 
things that you can do with C macros that you can't readily do in D (though 
there are a lot of things that yo ucan do with D templates that you could never 
do with C macros or even C++ templates - or if you can, it's a _lot_ harder in 
C++). It's a lot safer and less error-prone that way though.

In this case, you could do something like this:

int width;
int height;

func(width = 2, height = 7);

That _is_ a bit wasteful though in that it's assigning to local variables which 
are likely never used after that. Regardless, I don't think that you can do 
something quite like what you're trying to do. If nothing else, I don't think 
that D has anything like C99's designated initializers. It has constructors.

- Jonathan M Davis


More information about the Digitalmars-d mailing list