Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any Solution to Unpack a Vector to Function Arguments in C++?

Tags:

c++

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.

like image 464
Danqi Wang Avatar asked Jun 15 '12 04:06

Danqi Wang


1 Answers

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.

like image 153
R. Martinho Fernandes Avatar answered Sep 22 '22 01:09

R. Martinho Fernandes