Use template functions within mixin

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jun 6 08:21:12 PDT 2017


On Tuesday, June 06, 2017 15:00:50 Timoses via Digitalmars-d-learn wrote:
> Hey there,
>
> I'm wondering how I can use a template function within my mixin:
>
> ```
>                  ubyte[] value = x[33, 3a,3f, d4];
>                  foreach (type; TypeTuple!("int", "unsigned int",
> "byte"))
>                  {
>                      mixin(`if (value.length == type.sizeof)
>                              {
>                                  ubyte[type.sizeof] raw =
> value[0..$];
>                                  auto fValue =
> raw.littleEndianToNative!(type);
>                                  displayinfo(fValue);
>                              }
>                              break;
>                          `);
>                  }
> ```
>
>
> Error: template std.bitmanip.littleEndianToNative cannot deduce
> function from argument types !("int")(ubyte[8]), candidates are:
> [..]\src\phobos\std\bitmanip.d(2560,3):
> std.bitmanip.littleEndianToNative(T, uint n)(ubyte[n] val) if
> (canSwapEndianness!T && n == T.sizeof)
>
> ```
> `raw.littleEndianToNative!` ~ type ~ `;`
> ```
>
> neither works..
>
> Any way to accomplish this?

Well, for starters, I see no reason to even use mixins here. Just do

    foreach(type; TypeTuple!(int, uint, byte))
    {
    }

and write the code normally. Also, unsigned int isn't a type in D. It's
uint. And with what you have, mixing in "type.sizeof" is just going to
result in getting size of the type string. You'd need to do something like
"ubyte[" ~ type ~ "].sizeof] raw =" if you wanted to have the value of type
mixed in. Also, FYI, TypeTuple was renamed to AliasSeq, so that's what's
normally used now (though TypeTuple wasn't deprecated because of the amount
of existing code that uses it, so it will still work).

In any case, there's really no reason to be using string mixins here.
TypeTuple/AliasSeq and foreach will work with the actual types.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list