Comptime code to create a tuple from an array

I am confused on where you intend to get the runtime arguments for your function invocation from, I don’t think your post explicitly mentions this?

When you have a function type you can use std.meta.ArgsTuple to extract the corresponding tuple type for the parameters, that you can use to call that function.

Once you have that tuple type you need to create an instance of that type.

Does this mean you have something like an array of int parameters and want to turn that into a tuple instance?

You can do that by creating code that first creates the tuple type and then creates an instance of that tuple type. Here is an example of something like that:

const std = @import("std");

fn BuildTupleFromArray(comptime Array: type) type {
    const Element = std.meta.Elem(Array);
    const len = @typeInfo(Array).array.len;
    const types_array: [len]type = @splat(Element);
    return std.meta.Tuple(&types_array);
}

fn buildTupleFromArray(array: anytype) BuildTupleFromArray(@TypeOf(array)) {
    var a: BuildTupleFromArray(@TypeOf(array)) = undefined;
    inline for (&array, 0..) |value, i| {
        a[i] = value;
    }
    return a;
}

pub fn calc(a: i32, b: i32, c: i32) i32 {
    return a * 2 + b * b + c * 94 + 13;
}

pub fn main() !void {
    const tuple = buildTupleFromArray([_]i32{ 123, -379, 22 });
    std.debug.print("tuple: {}\n", .{tuple});

    const result = @call(.auto, calc, tuple);
    std.debug.print("result: {}\n", .{result});
}

Let me know if there is something else you are trying to accomplish.


You also might want to look at some older topics that do interesting/related things with tuples:

1 Like