Passing arguments to another variadic function

走远了吗. 提交于 2019-12-05 16:19:25

I suspect you have misunderstood the meaning of the signature

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

I suspect you think that fct() expect a int single value (index) and a variadic list of int's (indexex...) with C++11 style of parameter pack expansion.

No: it's the same as

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

so two int single values and a C-style of optional argument that you can use only through va_list stuff.

If you don't believe it, try calling fct() with only an integer argument

fct(1);

You should obtain an error of type "error: no matching function for call to 'fct'" with a note of type "note: candidate function not viable: requires at least 2 arguments, but 1 was provided" regarding the variadic version of fct().

If you want receive a variadic list of parameters and recursively pass the to the same function, you can use the template variadic way.

By example

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

If you really dislike the idea of a template, I guess you could cheat a bit like this:

#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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!