D import idiom compilation time
Simen Kjærås
simen.kjaras at gmail.com
Fri Jan 4 18:04:36 UTC 2019
On Friday, 4 January 2019 at 13:07:14 UTC, Rubn wrote:
> On Thursday, 3 January 2019 at 23:54:42 UTC, SrMordred wrote:
>> There is a veredict about the compilation speedup of the "New
>> Import Idiom"?
>>
>> Currently i´m using it this way:
>>
>> struct _std
>> {
>> template opDispatch(string moduleName)
>> {
>> mixin("import opDispatch = std." ~ moduleName ~ ";");
>> }
>> }
>> ...
>> //if used single time on scope.
>> _std.algorithm.max(a,b);
>>
>> My question is that, in the long run, this will be worth the
>> compilation time gains, or is just negligible and I should
>> just import the normal way.
>> (and keep the code more sane)
>>
>> Thanks!
>
> I like this idiom way more than the other nasty from!"..."
> syntax. Though you need to define a struct for any library
> you'd want to use it with, not that big of a deal. Thanks for
> sharing.
The struct could of course be templated:
struct from(string namespace) {
template opDispatch(string subnamespace) {
mixin("import opDispatch =
"~namespace~"."~subnamespace~";");
}
}
unittest {
alias std = from!"std";
std.stdio.writeln("ohai");
}
And slightly more fancy, for those pesky nested packages:
struct from(string namespace) {
static if (__traits(compiles, { mixin("import
"~namespace~";"); })) {
mixin("import __from = "~namespace~";");
}
template opDispatch(string subnamespace) {
static if (__traits(compiles, { mixin("import
"~namespace~"."~subnamespace~";"); })) {
alias opDispatch = .from!(namespace~"."~subnamespace);
} else {
mixin("alias opDispatch = __from."~subnamespace~";");
}
}
}
unittest {
alias std = from!"std";
std.stdio.writeln("ohai");
// This would be impossible with the first version:
static assert(std.range.primitives.isInputRange!(int[]));
// As would single-level imports:
alias myLibrary = from!"myLibrary";
myLibrary.someFunction();
}
--
Simen
More information about the Digitalmars-d
mailing list