【问题标题】:Passing arguments to another variadic function将参数传递给另一个可变参数函数
【发布时间】:2018-10-22 11:56:37
【问题描述】:

有没有什么办法可以让这段代码在不使用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;
}

【问题讨论】:

  • 您是否考虑过将fct 设为可变参数模板函数?
  • 这将如何解决我的问题?这不会使事情复杂化吗?到目前为止,我想要实现的目标似乎非常简单。
  • 事实是,我不能在这里使用可变参数模板,因为我已经这样做了。上面的代码非常简化以解决我的问题的核心,但我正在处理的真实代码有一个 std::size_t 可变参数模板。我想在没有模板的情况下解决这个问题。
  • 我不确定我是否遵循。你为什么不能把它做成一个模板?
  • @cantordust 我在这里提出了我的问题:stackoverflow.com/questions/50307095/…

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


【解决方案1】:

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

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

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

否:it's the same as

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

所以 两个 int 单个值和一个 C 风格的可选参数,您只能通过 va_list 东西使用。

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

fct(1);

你应该得到一个类型为“error: no matching function for call to 'fct'”的错误,并附上关于可变参数的注释“note: Candidate function notifiable: requires at least 2 arguments, but 1 was provided” fct() 的版本。

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

举例

template <typename ... Ts>
void fct(int index, Ts ... indexes)
{
    std::cout << index << ' ';
    fct(indexes...);
}

【讨论】:

  • 还可以输入void fct(){ std::cout &lt;&lt; std::endl; } 来打印endl
  • 感谢您的回复。换句话说,如果没有模板和va_list,绝对没有办法解决这个问题:\
  • @Pippin - 不,据我所知。或者更好:方式(从 C++11 开始)是可变参数模板之一。我不明白你用可变参数模板方式出了什么问题。
  • @max66 我在这里提出了我的问题:stackoverflow.com/questions/50307095/…
  • @Pippin - 正如您在我在新问题中的回答中看到的那样,可变参数模板的使用非常简单。
【解决方案2】:

如果你真的不喜欢模板的想法,我想你可以这样作弊:

#include <iostream>
#include <vector>

void fct(std::vector<int>&& _indices)
{
    for (auto&& i : _indices)
    {
        std::cout << i << ' ';
    }
    std::cout << std::endl;
}

int main(void)
{
    fct({1, 2, 3, 4, 5, 6, 7}); // Note the curly braces
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-01
    相关资源
    最近更新 更多