A list of arguments of variable length. How to understand that we got the last argument?

I have a Polynomial class that contains the coefficients of a given polynomial. It is assumed that one of its overloaded constructors will receive these coefficients through a list of variable arguments.

 template <class T> Polynomial<T>::Polynomial(T FirstCoefficient, ...) { va_list ArgumentPointer; va_start(ArgumentPointer, FirstCoefficient); T NextCoefficient = FirstCoefficient; std::vector<T> Coefficients; while (true) { Coefficients.push_back(NextCoefficient); NextCoefficient = va_arg(ArgumentPointer, T); if (/* did we retrieve all the arguments */) // How do I implement this? { break; } } m_Coefficients = Coefficients; } 

I know that we usually pass an additional parameter that tells the recipient method the total number of parameters, or we pass a sentimental end parameter. But in order to keep things short and clean, I do not prefer to pass an additional parameter.

Is there a way to do this without changing the method signature in the example?

+4
source share
2 answers

In general, no, there is no way to know when you press the last argument, and you need to provide some kind of watch. For this reason, variable length argument lists are inherently unsafe; There is no way to statically verify that all arguments are received correctly or that they have the correct types, etc. If you look at most varargs functions, they all have some way of knowing how many arguments are. printf and scanf use the format string, open scans the type of operation, etc.

In C ++ 0x, however, you can do this using std::initializer_list , which is a smarter, more type-safe alternative to varargs. For instance:

 template <class T> Polynomial<T>::Polynomial(T FirstCoefficient, std::initializer_list<T> coeffs) { m_coefficients.insert(m_coefficients.begin(), coeffs.begin(), coeffs.end()); } 

Now the compiler can enter: verify that all arguments are of type T and conduct all range checks.

+8
source

No, and this applies to all data structures (the argument list is just another data structure). You have 3.5 options:

  • Static, specified length.
  • Sentinel Value.
  • The data structure includes its length.
    3.5. The data structure inherently provides some way to safely get the length before you reach the end of the data structure.

Regardless, your decision comes down to one of these options.

+2
source

Source: https://habr.com/ru/post/1334850/


All Articles