Template mixins and selective imports
jmh530 via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Aug 3 13:47:01 PDT 2017
On Thursday, 3 August 2017 at 19:05:47 UTC, Meta wrote:
> On Thursday, 3 August 2017 at 19:03:55 UTC, Meta wrote:
>> `mixin vectorize!sin vsin; alias sin = vsin;` and see if it
>
> Should be `alias sin = vsin.sin;`
Thanks, this pointed me in the right direction. I got the line
below working.
mixin vectorize!sin temp;
alias vsin = temp.sin;
auto z = vsin(x);
I couldn't give it the name of sin or the name of the identifier.
This is a little ugly and would require the user to make the
adjustment themselves.
Below seems to work if the user doesn't import the relevant
function, though it will still result in errors if they
selectively import that function. I think the combination of the
two will be sufficient.
private enum _vectorizeAlt(string mod, string func) = "
auto " ~ func ~ "(SliceKind kind, size_t[] packs, Iterator)
(Slice!(kind, packs,
Iterator) slice)
{
import mir.ndslice.topology : map;
return slice.map!(" ~ mod ~ "." ~ func ~ ");
}
";
mixin template vectorizeAlt(string mod, string func)
{
mixin("static import " ~ mod ~ ";");
import mir.ndslice.slice : SliceKind, Slice;
mixin(_vectorizeAlt!(mod, func));
}
unittest
{
import std.stdio : writeln;
import mir.ndslice.slice : sliced;
import mir.ndslice.topology : map;
auto x = [0.0, 1.0, 2.0, 3.0].sliced;
mixin vectorizeAlt!("std.math", "sin");
auto y = sin(x);
}
More information about the Digitalmars-d-learn
mailing list