将std :: vector展开到参数包中 [英] Expand std::vector into parameter pack

查看:180
本文介绍了将std :: vector展开到参数包中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有带有以下签名的方法:

I have methods with the following signature:

void DoStuff(int i);
void DoStuff(int i, k);
void DoStuff(int i, int k, int l);

我有一个要从其中调用DoStuff方法的方法,如下所示:

I have a method from where I would like to call the DoStuff methods as follows:

void CallDoStuff(const std::vector<int>& vElements) {
  // What magic is supposed to happen here to make vElements an expandable pack?
  DoStuff(vElemets...);
}

有没有机会实现这一目标? 使用std :: index_sequence是否正确?如果是,请您提供一个简单的示例,将其应用于我的问题吗?

Is there any chance to achieve this? Is using std::index_sequence the right way? If yes, could you please provide me a simple example how to apply this to my problem?

推荐答案

有可能,只要您提供参数数目的上限即可.

It's possible, as long as you provide an upper bound to the number of arguments.

使用 Xeo对C ++ 11的std::index_sequence的实现:

template <unsigned... Idx>
void trampoline(const std::vector<int>& vElements, seq<Idx...>) {
    return DoStuff(vElements[Idx]...);
}

template <std::size_t Arity>
void trampoline(const std::vector<int>& vElements) {
    return trampoline(vElements, typename gen_seq<Arity>::seq{});
}

template <unsigned... Idx>
void CallDoStuff(const std::vector<int>& vElements, seq<Idx...>) {
    using trampoline_t = void (*)(const std::vector<int>&);
    constexpr trampoline_t trampolines[]{
        trampoline<Idx>...
    };
    trampolines[vElements.size()](vElements);
}

template <std::size_t Max>
void CallDoStuff(const std::vector<int>& vElements) {
    assert(vElements.size() <= Max);
    return CallDoStuff(vElements, typename gen_seq<Max + 1>::seq{});
}

在Wandbox上直播

这篇关于将std :: vector展开到参数包中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆