Extend the call site default argument expansion mechanism?

JN 666total at wp.pl
Thu May 10 14:28:39 UTC 2018


On Thursday, 10 May 2018 at 14:15:18 UTC, Yuxuan Shui 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?

For things like this you can use the OOP Factory pattern, 
pseudocode:

class DataStructureFactory
{
   this(Allocator alloc)
   {
     this.alloc = alloc;
   }

   Allocator alloc;

   DataStructure createDataStructure(...)
   {
     return new DataStructure(..., alloc)
   }
}

DataStructureFactory factory = new DataStructureFactory(new 
SomeAllocator())
auto data1 = factory.createDataStructure(...)
auto data2 = factory.createDataStructure(...)
auto data3 = factory.createDataStructure(...)


More information about the Digitalmars-d mailing list