Пространства имён
Варианты
Действия

Variadic functions

Материал из cppreference.com

Variadic функции являются функциями (например, std::printf), которые принимают переменное число аргументов.
Original:
Variadic functions are functions (e.g. std::printf) which take a variable number of arguments.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Содержание

[править] Статистика

Чтобы объявить Вариативный функции, многоточие используется в качестве последнего параметра, например, int printf(const char *format, ...);. Параметры, передаваемые переменным числом функций можно получить с помощью следующих макросов и типов
Original:
To declare a variadic function, an ellipsis is used as the last parameter, e.g. int printf(const char *format, ...);. Parameters passed to a variadic function can be accessed using the following macros and types:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Определено в файле <cstdarg>
позволяет получить доступ к переменным числом аргументов функции
Original:
enables access to variadic function arguments
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(функция-макрос) [edit]
доступ к следующим переменным числом аргументов функции
Original:
accesses the next variadic function argument
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(функция-макрос) [edit]
(C++11)
makes a copy of the variadic function arguments
(функция-макрос) [edit]
заканчивается обход переменным числом аргументов функции
Original:
ends traversal of the variadic function arguments
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(функция-макрос) [edit]
содержит информацию, необходимую va_start, va_arg, va_end, и va_copy
Original:
holds the information needed by va_start, va_arg, va_end, and va_copy
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(класс) [edit]

[править] По умолчанию преобразований

Когда Вариативный функция вызывается, после именующее к RValue, массива в указатель, и функция в указатель преобразований, каждый аргумент, который является частью списка переменных аргументов подвергается дополнительных преобразований известный как акциях аргумент по умолчанию " ':
Original:
When a variadic function is called, after lvalue-to-rvalue, array-to-pointer, and function-to-pointer преобразований, each argument that is a part of the variable argument list undergoes additional conversions known as default argument promotions:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Только арифметика, перечислением, указателем, указателем на член, и аргументы типа класса допускаются.
Original:
Only arithmetic, enumeration, pointer, pointer to member, and class type arguments are allowed.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[править] Альтернативы

  • Variadic шаблоны также может быть использован для создания функций, которые принимают переменное число аргументов. Они часто являются лучшим выбором, потому что они не накладывают ограничения на типы аргументов, не выполняют интегральные и с плавающей точкой акциях, и типа безопасно. (начиная с C++11)
    Original:
    Variadic templates can also be used to create functions that take variable number of arguments. They are often the better choice because they do not impose restrictions on the types of the arguments, do not perform integral and floating-point promotions, and are type safe. (начиная с C++11)
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Если все переменные аргументы общий тип, std::initializer_list обеспечивает удобный механизм (хотя и с другой синтаксис) для доступа к переменной аргументы.
    Original:
    If all variable arguments share a common type, a std::initializer_list provides a convenient mechanism (albeit with a different syntax) for accessing variable arguments.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

[править] Пример

#include <iostream>
#include <cstdarg>
 
void simple_printf(const char *fmt, ...)
{
    va_list args;
    va_start(args, fmt);
 
    while (*fmt != '\0') {
        if (*fmt == 'd') {
            int i = va_arg(args, int);
            std::cout << i << '\n';
        } else if (*fmt == 'c') {
            // note automatic conversion to integral type
            int c = va_arg(args, int);
            std::cout << static_cast<char>(c) << '\n';
        } else if (*fmt == 'f') {
            double d = va_arg(args, double);
            std::cout << d << '\n';
        }
        ++fmt;
    }
 
    va_end(args);
}
 
int main()
{
    simple_printf("dcff", 3, 'a', 1.999, 42.5);
}

Вывод:

3
a
1.999
42.5