<cstdarg>
The <cstdarg>
header is the C++ version of the C standard <stdarg.h>
header, which declares macros
for accessing the arguments to a function that takes a variable number
of arguments, that is, a function that is declared with an ellipsis as
the last parameter.
A function that takes a variable number of arguments (called a
variadic function) must have some way of knowing
how many arguments have actually been passed to the function and what
their types are. For example, the printf
function (in <cstdio>
) uses its format string to
determine the number and type of arguments.
Example 13-8 shows how
a function can use the <cstdarg>
macros. The max
function takes at least two arguments. The
first is a count of the number of remaining arguments; the count must be
positive. The template parameter specifies the type of each argument
that follows the count.
#include <cassert> #include <cstdarg> // Use a trivial wrapper class to ensure that va_end is called. class varargs { public: ~varargs( ) { va_end(ap); } std::va_list& ap; }; template <typename T> T max(unsigned count, ...) { assert(count > 0); varargs va; va_start(va.ap, count); T result = va_arg(va.ap, T); // Get first argument. while (--count > 0) { T arg = va_arg(va.ap, T); // Get successive arguments. if (arg > result) result = arg; // Remember the largest. } return result; } int main( ) { int a, b, c, d; ... int x = max<int>(4, a, b, c, d); int y = max<int>(2, ...
Get C++ In a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.