#Is it possible to have comptime type inference as a fn return without passing the type as argument?

1 messages · Page 1 of 1 (latest)

dark osprey
#

Consider this:

fn foo(T: type) T {
    if (T == i64) {
        return 1;
    }
    return 2;
}
test "foo" {
    const i = foo(i32);
    const j = foo(i64);
    std.debug.print("{d} ({})\n", .{ i, @TypeOf(i) }); //prints 2 (i32)
    std.debug.print("{d} ({})\n", .{ j, @TypeOf(j) }); //prints 1 (i64)
}

is it possible to have this functionality without having to pass the parameter T, and having it be inferred from the usage? like so:

fn bar() T {
    if (T == i64) {
        return 1;
    }
    return 2;
}

test "bar" {
    const i: i32 = bar();
    const j: i64 = bar();
    std.debug.print("{d} ({})\n", .{ i, @TypeOf(i) }); //prints 2 (i32)
    std.debug.print("{d} ({})\n", .{ j, @TypeOf(j) }); //prints 1 (i64)
}
real remnant
#

maybe return a comptime_int?