How to check that import module will succeed?

Paul Backus snarwin at gmail.com
Fri Jul 26 14:19:05 UTC 2019


On Friday, 26 July 2019 at 03:42:58 UTC, Andrey Zherikov wrote:
> Is there a way to check whether some module, say "foo", is 
> available for import before doing "import foo"?
> I want to create a function that imports module if it's 
> available or does something else otherwise. So I think the code 
> should look something like this:
>
> mixin template my_import(alias module_name)
> {
>     if(module_name is available)
>         mixin("import "~module_name~";");
>     else
>         pragma(msg, module_name~" is not available");
> }
>
> mixin my_import!("std.stdio");      // == import std.stdio
> mixin my_import!("unknown_module"); // == pragma(msg, 
> "unknown_module is not available")

version(HasStdio)
     import std.stdio;
else
     pragma(msg, "std.stdio is not available");

Then configure your build system to pass `-version=HasStdio` to 
dmd (or the equivalent flag to ldc or gdc) when std.stdio is 
available.


More information about the Digitalmars-d-learn mailing list