0

I would like to create the following C++ snipper in Rust. I am new to Rust and all I know so far is that the language does not support variadic arguments as in C++.

template <typename F, typename... Args>
void foo(F f, Args... args) {
    f(args...);
}


int f1(int num) { 
    // do something particular of f1 
}

int f2(int num, std::string myString) { 
    // do something particular of f2 
}

std::string f3(/* Unknow number of arguments and types*/) {
    // some procedure
}

int main() {
    foo(f1, 5);

    foo(f2, 5, "This is a string");

    foo(f3, 5, 4.6, "String", new std::vector(10));

    return 0;
}

I wonder what would be the work around. The main idea is to store/forward a function or method with unknown number of parameters and potentially different types, such that some sort of handler receive the arguments in another moment and pass them to the previously stored function.

As in the snipped, foo(..) would be in charge of conveying the function and the arguments that may come from different places and moments.

foo(..) should be able to receive any function with arbitrary arguments and types that fit the function f

Andres
  • 1
  • 1
  • You may be able to accomplish this with a tuple as the second argument, but probably not without the unstable `fn_traits` feature. – PitaJ Sep 15 '22 at 20:09
  • What you want will depend on what you want to do with `f` and `args`. If you just want the arguments in order to call the function later, then this is not the right pattern. Simple accept a generic `F: Fn() -> i32` and call it `f()`. You would pass in functions for `f1` and `f2` like `|| f1(5)` and `|| f2(5, 3)`. – kmdreko Sep 15 '22 at 21:24

0 Answers0