Passing a generic function as a parameter

Say I want to make a function to test sorting algorithms, Every sorting algorithm has the signature:

fn sort(comptime T: type, arr: []T) void

The testing function then has signature:

fn testSort(sort: fn (comptime T: type, arr: []T) void

However, Zig complains that T is not declared in arr: []T. What do I need to do to achieve something like this?

  1. using anytype:
fn testSort(sort: anytype) void {
    const ti = @typeInfo(@TypeOf(sort));
    assert(ti == .Fn);
    assert(ti.Fn.params.len == 2);
    const T = ti.Fn.params[0].type.?;
    ...
}
  1. using an additional argument:
fn testSort(comptime T: type, sort: fn (T: type, arr: []T) void) void {
     ...
}
4 Likes