I am actually thinking of something similar to the '*' operator in python like this:
args = [1,2,4]
f(*args)
Is there a similar solution in C++?
What I can come up with is as follows:
template <size_t num_args, typename FuncType>
struct unpack_caller;
template <typename FuncType>
struct unpack_caller<3>
{
void operator () (FuncType &f, std::vector<int> &args){
f(args[0], args[1], args[3])
}
};
Above I assume only int
argument type.
The problem is that I feel it is a hassle to write all the specializations of unpack_caller for different value of num_args
.
Any good solution to this? Thanks.
You can use a pack of indices:
template <size_t num_args>
struct unpack_caller
{
private:
template <typename FuncType, size_t... I>
void call(FuncType &f, std::vector<int> &args, indices<I...>){
f(args[I]...);
}
public:
template <typename FuncType>
void operator () (FuncType &f, std::vector<int> &args){
assert(args.size() == num_args); // just to be sure
call(f, args, BuildIndices<num_args>{});
}
};
There's no way to remove the need to specify the size in the template though, because the size of a vector is a runtime construct, and we need the size at compile-time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With