Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...