将参数传递给另一个可变参数函数

时间:2018-05-12 04:48:43

标签: c++ parameter-passing c++17 ellipsis variadic

这个代码是否有任何方法可以在不诉诸va_list的情况下按预期编译和工作?

#include <iostream>

void fct(void)
{
    std::cout << std::endl;
}

void fct(int index, int indexes...)
{
    std::cout << index << ' ';
    fct(indexes); //or fct(indexes...); ?
}

int main(void)
{
    fct(1, 2, 3, 4, 5, 6, 7);
    return 0;
}

1 个答案:

答案 0 :(得分:2)

我怀疑你误解了签名的含义

void fct (int index, int indexes...)

我怀疑您认为fct()期望int单个值(index)和int indexex... void fct (int index, int indexes, ...) 的可变列表)使用C ++ 11样式的参数包扩展。

否:it's the same as

int

所以两个 va_list单个值和一个C风格的可选参数,只能通过fct()内容使用。

如果您不相信,请尝试仅使用整数参数调用fct(1);

fct()

您应该获得类型&#34的错误;错误:没有匹配函数来调用&#39; fct&#39;&#34;注意类型&#34;注意:候选函数不可行:需要至少2个参数,但提供了1个&#34;关于template <typename ... Ts> void fct(int index, Ts ... indexes) { std::cout << index << ' '; fct(indexes...); } 的可变版本。

如果要接收可变参数列表并递归传递给同一个函数,可以使用模板可变方式。

以示例

// {k1,...,k16} are the divs' ids and kart is div's classname
$(document).ready(function() {
  $("button").click(function() {
    $("#k1").html("2");
    $("#k2").html("3");
    $("#k3").html("1");
    $("#k4").html("3");
    $("#k5").html("5");
    $("#k6").html("6");
    $("#k7").html("1");
    $("#k8").html("6");
    $("#k9").html("4");
    $("#k10").html("7");
    $("#k11").html("8");
    $("#k12").html("8");
    $("#k13").html("5");
    $("#k14").html("7");
    $("#k15").html("2");
    $("#k16").html("4");
  });

});

function myFunction() {
  setTimeout(function() {
    $('.kart').empty();
  }, 4000);
}