Extend the call site default argument expansion mechanism?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Fri May 11 14:26:21 UTC 2018


On Thursday, May 10, 2018 14:15:18 Yuxuan Shui via Digitalmars-d wrote:
> So in D I can use default argument like this:
>
> int f(int line=__LINE__) {}
>
> And because default argument is expanded at call site, f() will
> be called with the line number of the call site.
>
> This is a really clever feature, and I think a similar feature
> can be useful in other ways.
>
> Say I need to construct a bunch of data structure that takes an
> Allocator argument, I need to do this:
>
> ...
> auto alloc = new SomeAllocator();
> auto data1 = new DataStructure(..., alloc);
> auto data2 = new DataStructure(..., alloc);
> auto data3 = new DataStructure(..., alloc);
> ...
>
> This looks redundant. But if we have the ability to define more
> special keywords like __LINE__, we can do something like this:
>
> ...
> // constructor of DataStructure
> this(Allocator alloc=__ALLOC__) {...}
> ...
> auto alloc = new SomeAllocator();
> define __ALLOC__ = alloc;
> // And we don't need to pass alloc everytime
> ...
>
> Is this a good idea?

It seems like really risky move, honestly, because it means that the
function is then affected by what is and isn't declared within the scope
where it's called. __FILE__ and __LINE__ are well-defined as to what they
mean. No can declare them to mean something else. You don't have symbol
resolution issues or naming conflicts. And they're solving a problem that
can't actually be solved without compiler help. However, if you just want to
change what arguments get passed to foo within your module, all you have to
do is define another foo inside the module and have it forward to the
original one with whatever arguments you want. What you're suggesting here
seems to introduce name pollution issues without solving anything that can't
easily be solved with the language as-is.

- Jonathan M Davis



More information about the Digitalmars-d mailing list