Variadic functions
Da cppreference.com
![]() |
This page has been machine-translated from the English version of the wiki using Google Translate.
The translation may contain errors and awkward wording. Hover over text to see the original version. You can help to fix errors and improve the translation. For instructions click here. |
Variadic funções são funções (std::printf, por exemplo) que levam um número variável de argumentos.
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.
You can help to correct and verify the translation. Click here for instructions.
Índice |
[editar] Uso
Para declarar uma função aridade, uma elipse é usado como o último parâmetro, por exemplo, int printf(const char *format, ...);. Os parâmetros passados para uma função de aridade variável pode ser acessada usando as seguintes macros e tipos:
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.
You can help to correct and verify the translation. Click here for instructions.
Defined in header
<cstdarg> | |
permite o acesso a argumentos de função variádicos 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. (função macro) | |
acessa o argumento da função próximo aridade 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. (função macro) | |
(C++11) |
makes a copy of the variadic function arguments (função macro) |
termina travessia dos argumentos da função variádicos 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. (função macro) | |
detém as informações necessárias va_start, va_arg, va_end, e 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. (classe) |
[editar] Conversões padrão
Quando uma função aridade é chamado, depois lvalue-a-rvalue, array para ponteiro, e função para ponteiro-conversões, cada argumento de que é uma parte da lista de argumentos variável sofre conversões adicionais conhecidos como promoções de argumento padrão ' ':
Original:
When a variadic function is called, after lvalue-to-rvalue, array-to-pointer, and function-to-pointer conversões, 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.
You can help to correct and verify the translation. Click here for instructions.
- std::nullptr_t é convertido para void*Original:std::nullptr_t is converted to void*The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - float argumentos são convertidos para double como em de ponto flutuante promoçãoOriginal:The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - bool, char, enumerações short, e sem escopo são convertidos para int ou mais amplos tipos inteiros como em promoção inteiroOriginal:bool, char, short, and unscoped enumerations are converted to int or wider integer types as in promoção inteiroThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Aritmética só, enumeração, ponteiro, ponteiro para membro, e argumentos de tipo de classe são permitidos.
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.
You can help to correct and verify the translation. Click here for instructions.
[editar] Alternativas
- Templates Variadic também pode ser usado para criar funções que recebem um número variável de argumentos. Eles são muitas vezes a melhor escolha, porque eles não impõem restrições sobre os tipos de argumentos, não realizar promoções integrais e de ponto flutuante, e são do tipo seguro. (desde 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. (desde C++11)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Se todos os argumentos variáveis compartilhar um tipo comum, um std::initializer_list fornece um mecanismo conveniente (embora com uma sintaxe diferente) para acessar argumentos variáveis .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.
[editar] Exemplo
#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); }
Saída:
3 a 1.999 42.5