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.
source share