I'm want to be able to avoid code duplication when writing Rust template code to work with variadic number of template parameters, like so:
fn to_c_function_0<C>(closure: Box<C>) -> unsafe extern "C" fn(*mut c_void)
where
C: FnMut(),
{
unimplemented!()
}
fn to_c_function_1<C, Arg0>(closure: Box<C>) -> unsafe extern "C" fn(*mut c_void, Arg0)
where
C: FnMut(Arg0),
{
unimplemented!()
}
fn to_c_function_2<C, Arg0, Arg1>(closure: Box<C>) -> unsafe extern "C" fn(*mut c_void, Arg0, Arg1)
where
C: FnMut(Arg0, Arg1),
{
unimplemented!()
}
// and so on...
Is it possible to reduce code duplication without macros? How?
I was thinking it could be possible with a tuple of arguments (similar to Is it possible to emulate variadic generics in Rust?) but don't know if that's possible
Edit:
The tuple of arguments solutions doesn't seem to work
use std::os::raw::*;
type CFunction0 = unsafe extern "C" fn(*mut c_void);
type CFunction2 = unsafe extern "C" fn(*mut c_void, c_int, *const c_char);
fn to_c_function<C, Arg>(closure: Box<C>) -> unsafe extern "C" fn(*mut c_void, Arg)
where
C: FnMut(Arg),
{
unsafe extern "C" fn call<Arg>(data: *mut c_void, arg0: Arg) {}
call::<Arg>
}
fn main() {
// all lines below fail to compile
let c_0_a: CFunction0 = to_c_function(Box::new(|()| {}));
let c_0_b: CFunction0 = to_c_function(Box::new(|| {}));
let c_1_a: CFunction2 = to_c_function(Box::new(|(x, y)| {}));
let c_1_b: CFunction2 = to_c_function(Box::new(|x, y| {}));
}