Pippin
Pippin

Reputation: 333

Passing arguments to another variadic function

Is there any way at all for this code to compile and work as intended without resorting to va_list stuff ?

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

Upvotes: 4

Views: 302

Answers (2)

cantordust
cantordust

Reputation: 1612

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

Upvotes: 0

max66
max66

Reputation: 66230

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

Upvotes: 2

Related Questions