#comptime array of functions

1 messages · Page 1 of 1 (latest)

sly bridge
#

Is it possible to have a function take a comptime array/slice of functions (body, not pointer, with the same signature)? I am trying to get an arbitrary array of predicates unrolled at comptime where the predicate array size is known at comptime (rather than an array of function pointers). I specify the array size at the callsite but I'm getting an "unable to infer array size" error. This is a roughly distilled example of my current attempt. Thanks!

pub const predicate_t: type = fn (*std.ArrayList(u32)) u32;

// ...

pub fn apply_predicates(
  comptime predicates: [_]predicate_t, // ...
) u32 {
  // ...
  var result: u32 = 0;
  inline for (predicates) |p| {
    result += p(some_arg);
  }
  return result;
} 

// call like:
_ = apply_predicates([2]predicate_t{predicate1, predicate2});
lunar dock
#

[_]T syntax is only allowed within array initialisation (so the callsite argument can look like [_]predicate_t{ predicate1, predicate2 }).
for the function itself, you'll have to first take a length argument and use that:

pub fn apply_predicates(
  comptime length: usize,
  comptime predicates: [length]predicate_t,
) u32 {
    ...
}
```ideally you'll be able to pass in `[]const predicate_t`, to avoid the second argument, but Zig currently (in my opinion erroneously) forbids that type. you can also pass in a `[]const *const predicate_t` - yes, this is a slice of function *pointers*, but as long as it is comptime-known you can get the function *bodies* back by derefing the value