On Friday, 9 February 2018 at 15:50:24 UTC, Ralph Doncaster wrote:
On Friday, 9 February 2018 at 15:24:27 UTC, Mike Parker wrote:
On Friday, 9 February 2018 at 15:05:33 UTC, Ralph Doncaster wrote:
This seems odd to me. Is there a way I can make a function that takes an array of any type but only of a specific size in bytes?

void.d(8): Error: function void.foo (void[12] arr) is not callable using argument types (uint[3])
Failed: ["/usr/bin/dmd", "-v", "-o-", "void.d", "-I."]
void foo(void [12] arr)
{
}

void main()
{
    uint[3] arr;
    foo(arr);
}

void has no size, so what does it mean to have 12 of them?

according to the docs and my testing, the size of a void array element is 1,

Correct.

so the following code prints 12:
import std.stdio;

void foo(void [] arr)
{
    writeln("length: " arr.length);
}

void main()
{
    uint[3] arr;
    foo(arr);
}

I thought about using templates, but I was looking for a simple way of making a function that takes an array of 12 bytes, whether it is uint[3], ubyte[12], or ushort[6].

uint[3] and void[12] have the same size but are different types so the compiler will reject it. you can reinterpret cast them(i.e. *cast(void[12])(&arr) ), but this is a rather blunt tool. Is it safe in the case that the types size is at least 12 but not safe in general.

Is there a way I can make a function that takes an array of any type but only of a specific size in bytes?

With a template that constrains the types size:

void foo(T)(T t) if (T.sizeof == 12)
{
    //...
}

alternately reject incorrect values at runtime

void foo(ubyte[] t)
in
{
    assert(t.length == 12);
}
do
{
    //...
}

Reply via email to