Unknown number of arguments in function

argument-passing, c++, variadic-functions

Solution

Variable argument lists have several drawbacks:

- Callers can pass in everything they want.

- If a non-POD object is passed, undefined behaviour is summoned

- You can't rely on the number of arguments (the caller can make errors)

- You put a LOT of responsibility on your CLIENT, for whom you intended to have an easier time with your library code (practical example: format-string-bugs/-errors)

Compared to variadic templates:

- Compile time list size is known

- Types are known at compile time

- You have the responsibility for stuff, not your client, which is like it should be.

Example:

void pass_me_floats_impl (std::initializer_list<float> floats) {
    ...
}

You can put this into the private section of a class declaration or in some detail namespace. Note: `pass_me_floats_impl()` doesn't have to be implemented in a header.

Then here's the nice stuff for your client:

template <typename ...ArgsT>
void pass_me_floats (ArgsT ...floats) {
    pass_me_floats_impl ({floats...});
}

He now can do:

pass_me_floats ();
pass_me_floats (3.5f);
pass_me_floats (1f, 2f, 4f);

But he can't do:

pass_me_floats (4UL, std::string());

because that would emit a compile error inside your pass_me_floats-function.

If you need at least, say, 2 arguments, then make it so:

template <typename ...ArgsT>
void pass_me_floats (float one, float two, ArgsT... rest) {}

And of course, if you want it a complete inline function, you can also

template <typename ...ArgsT>
void pass_me_floats (ArgsT... rest) {
    std::array<float, sizeof...(ArgsT)> const floaties {rest...};

    for (const auto f : floaties) {}
}

Problem

I've got the class member: ``` LineND::LineND(double a ...) { coefficients.push_back(a); va_list arguments; va_start(arguments, a); double argValue; do { argValue = va_arg(arguments, double); coefficients.push_back(argValue); }while(argValue != NULL); // THIS IS A PROBLEM POINT! va_end(arguments); } ``` I don't know how many arguments will be used. I need to take each argument and put it into the vector called `coefficients`. How should I do that? I understand, that the statement `while(argValue != NULL)` is not correct in this case. I can't use for example this signature: ``` LineND::LineND(int numArgs, double a ...) ``` to change the condition like this: ``` while(argValue != numArgs); ``` The point is I can't change the signature of the method. Need to resolve this problem another way.

Original source

Related problems