Named multi-imports

Timon Gehr via Digitalmars-d digitalmars-d at puremagic.com
Fri Aug 18 02:18:42 PDT 2017


On 18.08.2017 03:11, Johnson Jones wrote:
>>>
>>
>> private struct oo{
>>     import std.stdio: writeln, write;
>>     import std.algorithm: filter, map;
>>     // …
>> }
>>
>> void main(){
>>     oo.write("result: ");
>> oo.writeln(oo.map!(x=>x/2)(oo.filter!(x=>x%2==0)([1,2,3,4,5,6,10])));
>> }
> 
> Wow, that might solve the problem! A little more verbose but it does 
> combine everything.
> 
> Any downsides?
> 

- It is more verbose. ;)


- IMAO it shouldn't even work without 'public' on the imports. (So if 
someone decides to fix that it might break and become more verbose.)


- It introduces a new type that would not really be necessary. This is 
avoidable, at the cost of a little more verbosity:


private template Imports(){
     public import std.stdio: writeln, write;
     public import std.algorithm: filter, map;
}
private alias oo = Imports!();

void main(){
     oo.write("result: ");
     oo.writeln(oo.map!(x=>x/2)(oo.filter!(x=>x%2==0)([1,2,3,4,5,6,10])));
}


The pattern can be abstracted into a utility template:

---
module util;

// ...

template Imports(T...){
     import std.string,std.algorithm;
     mixin([T].map!(x=>"public import "~x~";").join);
     // or, starting from DMD 2.076, you could use static foreach instead:
     // static foreach(x;T) mixin("public import "~x~";");
}

// ...

---

---
module main;

import util: Imports;
private alias oo = Imports!(
     `std.stdio: writeln, write`,
     `std.algorithm: filter, map`
);

void main(){
     oo.write("result: ");
     oo.writeln(oo.map!(x=>x/2)(oo.filter!(x=>x%2==0)([1,2,3,4,5,6,10])));	
}
---


> Thanks.

np.


More information about the Digitalmars-d mailing list