Espaços nominais
Variantes
Acções

Lambda functions (a partir do C++ 11)

Da cppreference.com
< cpp‎ | language


 
 
Linguagem C + +
Tópicos gerais
Original:
General topics
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Controle de fluxo
Original:
Flow control
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Declarações execução condicional
Original:
Conditional execution statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Instruções de iteração
Original:
Iteration statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Ir declarações
Original:
Jump statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Funções
Original:
Functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
declaração da função
lambda declaração da função
modelo de função
linha especificador
especificações de exceção (obsoleta)
noexcept especificador (C++11)
Exceções
Original:
Exceptions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Namespaces
Original:
Namespaces
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Tipos
Original:
Types
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
decltype specifier (C++11)
Especificadores
Original:
Specifiers
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
cv especificadores
armazenamento duração especificadores
constexpr especificador (C++11)
auto especificador (C++11)
alignas especificador (C++11)
Inicialização
Original:
Initialization
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Literais
Original:
Literals
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Expressões
Original:
Expressions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
representações alternativas
Utilitários
Original:
Utilities
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Tipos
Original:
Types
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
typedef declaration
tipo de alias declaração (C++11)
atributos (C++11)
Lança
Original:
Casts
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
conversões implícitas
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
Elenco C-estilo e funcional
Alocação de memória
Original:
Memory allocation
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Classes
Original:
Classes
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Classe propriedades específicas de função
Original:
Class-specific function properties
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Funções membro especiais
Original:
Special member functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Modelos
Original:
Templates
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
modelo de classe
modelo de função
especialização de modelo
pacotes de parâmetros (C++11)
Diversos
Original:
Miscellaneous
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Assembly embutido
 
Constrói um encerramento: um objeto função sem nome capaz de captar as variáveis ​​no escopo.
Original:
Constructs a encerramento: an unnamed function object capable of capturing variables in scope.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Índice

[editar] Sintaxe

[ capture ] ( params ) mutable exception attribute -> ret { body } (1)
[ capture ] ( params ) -> ret { body } (2)
[ capture ] ( params ) { body } (3)
[ capture ] { body } (4)
1)
Declaração completa
Original:
Full declaration
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
2)
Declaração de um lambda const: os objetos capturados por cópia não pode ser modificada.
Original:
Declaration of a const lambda: the objects captured by copy cannot be modified.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
3)
Omitido arrastando-tipo de retorno: o tipo de retorno operator() o fechamento é deduzida de acordo com as seguintes regras:
Original:
Omitted trailing-return-type: the return type of the closure's operator() is deduced according to the following rules:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • se o body consiste na declaração return único, o tipo de retorno é o tipo da expressão retornada (após rvalue-to-lvalue, matriz-to-ponteiro, ou uma função-para-ponteiro conversão implícita)
    Original:
    if the body consists of the single return statement, the return type is the type of the returned expression (after rvalue-to-lvalue, array-to-pointer, or function-to-pointer implicit conversion)
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • caso contrário, o tipo de retorno é void
    Original:
    otherwise, the return type is void
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
4)
Lista de parâmetros omitido: função não tem argumentos, como se a lista de parâmetros foi ()
Original:
Omitted parameter list: function takes no arguments, as if the parameter list was ()
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Explicação

mutable -
body permite modificar os parâmetros capturados por cópia, e chamar suas funções não-membro const
Original:
allows body to modify the parameters captured by copy, and to call their non-const member functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
exception -
fornece o especificação de exceção ou o noexcept cláusula de operador () do tipo de fecho
Original:
provides the especificação de exceção or the noexcept cláusula for operator() of the closure type
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
attribute -
fornece o especificação de atributo de operador () do tipo de fecho
Original:
provides the especificação de atributo for operator() of the closure type
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

{{par | capture |{{tr| especifica quais símbolos visíveis no âmbito em que a função é declarada será visível no interior do corpo da função. Uma lista de símbolos pode ser passado como se segue:

  • [a,&b] onde a é capturado por valor e b é capturado por referência.
  • [this] capta o [[CPP / linguagem / isso| specifies which symbols visible in the scope where the function is declared will be visible inside the function body.

A list of symbols can be passed as follows:

  • [a,&b] where a is captured by value and b is captured by reference.
  • [this] captures the [[cpp/language/this}}|this pointer]]
  • [&] captures all symbols by reference
  • [=] captures all by value
  • [] captures nothing }}
params -
A lista de parâmetros, como no nomeado funções
Original:
The list of parameters, as in nomeado funções
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
ret -
Tipo de retorno. Se não estiver presente é implícitos nas declarações de função de retorno (ou nulo se não devolver qualquer valor)
Original:
Return type. If not present it's implied by the function return statements ( or void if it doesn't return any value)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
body -
Corpo da função
Original:
Function body
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.


A expressão lambda constrói um objeto não identificado temporária de única sem nome não-união tipo não-agregado, conhecido como' tipo de fechamento, que tem os seguintes membros:
Original:
The lambda expression constructs an unnamed temporary object of unique unnamed non-union non-aggregate type, known as closure type, which has the following members:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

ClosureType ::
Original:
ClosureType::
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
operator()

ret operator()(params) const { body }
(a palavra-chave mutável não foi utilizado)
ret operator()(params) { body }
(a palavra-chave foi usada mutável)

Executes the body of the lambda-expression, when invoked. When accessing a variable, accesses its captured copy (for the entities captured by copy), or the original object (for the entities captured by reference). Unless the keyword mutable was used in the lamda-expression, the objects that were captured by copy are non-modifiable from inside this operator().

Dangling references

If an entity is captured by reference, implicitly or explicitly, and the function call operator of the closure object is invoked after the entity's lifetime has ended, undefined behavior occurs. The C++ closures do not extend the lifetimes of the captured references.

ClosureType ::
Original:
ClosureType::
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
operator ret(*)(params)

typedef ret(*F)(params);
operator F() const;

This member function is only defined if the capture list of the lambda-expression is empty.

The value returned by this conversion function is a function pointer that, when invoked, has the same effect as invoking the closure object's function call operator directly.

ClosureType ::
Original:
ClosureType::
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
ClosureType()

ClosureType() = delete;
ClosureType(const ClosureType& ) = default;
ClosureType(ClosureType&& ) = default;

Closure types are not DefaultConstructible. The copy constructor and the move constructor are implicitly-declared and may be implicitly-defined according to the usual rules for implicit copiar construtores and mover construtores.

ClosureType ::
Original:
ClosureType::
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
operator=()

ClosureType& operator=(const ClosureType&) = delete;

Closure types are not CopyAssignable.

ClosureType ::
Original:
ClosureType::
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
~ClosureType()

~ClosureType() = default;

The destructor is implicitly-declared.

ClosureType ::
Original:
ClosureType::
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
CapturedParam

T1 a;

T2 b;

...

If the lambda-expression captures anything by copy (either implicitly with capture clause [=] or explicitly with a capture that does not include the character &, e.g. [a, b, c]), the closure type includes unnamed non-static data members, declared in unspecified order, that hold copies of all entities that were so captured.

The type of each data member is the type of the corresponding captured entity, except if the entity has reference type (in that case, references to functions are captured as-is, and references to objects are captured as copies of the referenced objects).

For the entities that are captured by reference (with the default capture [&] or when using the character &, e.g. [&a, &b, &c]), it is unspecified if additional data members are declared in the closure type.

[editar] Exemplo

Este exemplo mostra como passar um lambda a um algoritmo genérico e que os objectos resultantes de uma declaração lambda, podem ser armazenados em objectos std::function .
Original:
This example shows how to pass a lambda to a generic algorithm and that objects resulting from a lambda declaration, can be stored in std::function objects.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

#include <vector>
#include <iostream>
#include <algorithm>
#include <functional>
 
int main()
{
    std::vector<int> c { 1,2,3,4,5,6,7 };
    int x = 5;
    c.erase(std::remove_if(c.begin(), c.end(), [x](int n) { return n < x; } ), c.end());
 
    std::cout << "c: ";
    for (auto i: c) {
        std::cout << i << ' ';
    }
    std::cout << '\n';
 
    std::function<int (int)> func = [](int i) { return i+4; };
    std::cout << "func: " << func(6) << '\n'; 
}

Output:

c: 5 6 7
func: 10

[editar] Veja também

auto especificador
especifica um tipo definido por uma (C++11) expressão
Original:
specifies a type defined by an expression (C++11)
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)
envolve objeto que pode ser chamado de qualquer tipo com a assinatura especificada função chamada
Original:
wraps callable object of any type with specified function call signature
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(modelo de classe) [edit]