Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

Any Solution to Unpack a Vector to Function Arguments in 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...