When you say specialize, do you mean keeping the same name and then dispatching to a special version of it? It sounds like you’re talking about a form of overloading (which in C++ is natively supported).
In your case, you could do:
const State = enum{ A, B, C };
fn foo(comptime state: State, x: i32) State {
switch(state) {
// handle code here
}
}
The issue here is that any individual state isn’t a type, it’s a value.
So, if you wanted to further, you could make specialized instantiations of functions ala “Tag Dispatch”…
const State = enum { A, B, C };
pub fn Dispatch(comptime state: State) type {
return struct {
pub fn call(x: i32) void {
return inner(state, x);
}
fn inner(comptime s: State, x: i32) void {
switch (s) {
.A => std.debug.print("\nState: {}, Value: {}", .{ s, x }),
.B => std.debug.print("\nState: {}, Value: {}", .{ s, x }),
.C => std.debug.print("\nState: {}, Value: {}", .{ s, x }),
}
}
};
}
pub fn main() !void {
// now specialized for only state B
const call = Dispatch(State.B).call;
call(42);
}
One thing this gains is the ability to define a function above a bunch of call sites. Say foo returned a number instead of a state…
const foo = Dispatch(state).call; // you could parameterize this
// use foo a bunch without having to specify the state each time.
const y = foo(foo(42) + foo(43));
// instead of...
const y = foo(state, foo(state, 42) + foo(state, 43));
Which could be handy in cleaning things up. Maybe could make things more maintainable under certain circumstances? The interface is a little restrictive, and you could make this a lot more complicated, but if you know your other parameters and your return type then a restrictive interface isn’t necessarily a bad thing.
If you took in a second parameter, call it func
, you could bind func
’s first argument instead of inner
. So…
// func's type can be specified more thorougly here...
pub fn Dispatch(comptime state: State, func: anytype) type {
return struct {
pub fn call(x: i32) State {
return func(state, x);
}
};
}
I’m not sure how you intend on using this otherwise, so I maybe need more clarification, but that’s just a few thoughts.