How to check that import module will succeed?

evilrat evilrat666 at gmail.com
Sat Jul 27 02:46:15 UTC 2019


On Friday, 26 July 2019 at 14:56:37 UTC, Andrey Zherikov wrote:
>
> Even without static if I get the same result:
> mixin template my_import(alias modName)
> {
>     mixin("import " ~ modName ~ ";");
> }
> mixin my_import!"mymod";
> pragma(msg,fullyQualifiedName!(myfunc));       // Error: 
> undefined identifier myfunc
> pragma(msg,fullyQualifiedName!(mymod.myfunc)); // mymod.myfunc
>
> If I understood template mixin doc correctly this happens 
> because of "The declarations in a mixin are placed in a nested 
> scope". So is there a way to make two use cases above to work 
> the same way, i.e. "myfunc" to be available without "mymod." 
> prefix?

Exactly. Because of scoping rules mixin templates are nearly 
useless, there was a lot of frustration/criticism on them, but 
this is by design - to not turn them in macro hell like in C.
My opinion is that if core team are so picky about explicitness 
they should also provide a way to explicitly mix into the current 
scope, but of course I'm just yet another stranger here.

So you can do string mixin instead, however it requires more 
labor, and usually one has to keep in mind all intricacies of the 
features used which quickly leads to complexity combinatory 
explosion.

But whatever... With helper function above you can try this

     @property string my_import(alias mod)()
     {
	return
	"static if (__traits(compiles, isModuleAvailable!\"" ~ mod ~ 
"\"))" ~
	"{" ~
	" mixin(\"import \",\"" ~ mod ~ "\", \";\"); " ~
	"}";
     }

     // should import into current scope
     mixin(my_import!"std.string");


More information about the Digitalmars-d-learn mailing list