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
939 views
in Technique[技术] by (71.8m points)

c++ - c++11: Calling a variadic function with the elements of a vector

There are plenty of questions about how to call a variadic function with the elements of a tuple. e.g: How do I expand a tuple into variadic template function's arguments? My problem is a bit different:

I have a family of functions:

void f(int arg1);
void f(int arg1, int arg2);
...

I'd like a template:

template<size_t Arity>
void call(std::vector<int> args) {
   ???
}

That calls the appropriate f with args[0], args[1]...

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Here's a working example:

#include <vector>

// indices machinery

template< std::size_t... Ns >
struct indices {
    typedef indices< Ns..., sizeof...( Ns ) > next;
};

template< std::size_t N >
struct make_indices {
    typedef typename make_indices< N - 1 >::type::next type;
};

template<>
struct make_indices< 0 > {
    typedef indices<> type;
};

void f(int) {}
void f(int, int) {}

// helper function because we need a way
// to deduce indices pack

template<size_t... Is>
void call_helper(const std::vector<int>& args, indices<Is...>)
{
    f( args[Is]... ); // expand the indices pack
}

template<std::size_t Arity>
void call(const std::vector<int>& args)
{
    if (args.size() < Arity) throw 42;
    call_helper(args, typename make_indices<Arity>::type());
}

int main()
{
    std::vector<int> v(2);
    call<2>(v);
}

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

...