Espaços nominais
Variantes
Acções

constexpr specifier (desde 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)
Conversões
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
 
  • constexpr - especifica que o valor de uma variável ou função pode ser calculado em tempo de compilação
    Original:
    constexpr - specifies that the value of a variable or function can be computed at compile time
    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

constexpr especificador declara que é possível avaliar o valor da função ou variável em tempo de compilação, então eles podem ser usados ​​onde apenas o tempo de compilação expressões constantes são permitidos. constexpr implica const.
Original:
constexpr specifier declares that it is possible to evaluate the value of the function or variable at compile time, they then can be used where only compile time expressões constantes are allowed. constexpr implies const.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
'constexpr variáveis' deve satisfazer os seguintes requisitos:
Original:
constexpr variables must satisfy the following requirements:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • deve ser imediatamente construídos ou atribuído um valor.
    Original:
    it must be immediately constructed or assigned a value.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • o construtor parâmetros ou o valor a ser atribuído deve conter apenas valores literais, variáveis ​​constexpr e funções.
    Original:
    the constructor parameters or the value to be assigned must contain only literal values, constexpr variables and functions.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • o construtor usado para construir o objeto (implícita ou explícita) deve satisfazer os requisitos do construtor constexpr. No caso do construtor explícito, deve ter constexpr especificado.
    Original:
    the constructor used to construct the object (either implicit or explicit) must satisfy the requirements of constexpr constructor. In the case of explicit constructor, it must have constexpr specified.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
'constexpr funções' deve satisfazer os seguintes requisitos:
Original:
constexpr functions must satisfy the following requirements:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • não deve ser virtual
    Original:
    it must not be virtual
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • seu tipo de retorno deve ser LiteralType
    Original:
    its return type must be LiteralType
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • cada um de seus parâmetros devem ser do tipo literal
    Original:
    each of its parameters must be literal type
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • o corpo da função deve ser excluído ou inadimplente ou conter apenas o seguinte:
    Original:
    the function body must be either deleted or defaulted or contain only the following:
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • declarações nulos
    Original:
    null statements
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • static_assert declarações
    Original:
    static_assert declarations
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • typedef declarações e declarações alias que não definem classes ou enumerações
    Original:
    typedef declarations and alias declarations that do not define classes or enumerations
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • usando declarações
    Original:
    using declarations
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • usando directivas
    Original:
    using directives
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • exatamente uma declaração return que contém somente os valores literais, variáveis ​​constexpr e funções.
    Original:
    exactly one return statement that contains only literal values, constexpr variables and functions.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
'constexpr construtor' deve satisfazer os seguintes requisitos:
Original:
constexpr constructor must satisfy the following requirements:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • cada um de seus parâmetros devem ser do tipo literal
    Original:
    each of its parameters must be literal type
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • a classe não deve ter classes base virtuais
    Original:
    the class must have no virtual base classes
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • o corpo do construtor deve ser excluído ou inadimplente ou conter apenas o seguinte:
    Original:
    the constructor body must be either deleted or defaulted or contain only the following:
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • declarações nulos
    Original:
    null statements
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • static_assert declarações
    Original:
    static_assert declarations
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • typedef declarações e declarações alias que não definem classes ou enumerações
    Original:
    typedef declarations and alias declarations that do not define classes or enumerations
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • usando declarações
    Original:
    using declarations
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • usando directivas
    Original:
    using directives
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • o construtor não deve ter um bloco try-função
    Original:
    the constructor must not have a function-try block
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • cada classe de base e todos os membros não-estático deve ser inicializado, seja no initializer_list ou inicializador de cinta-ou-igual. Terminar cada construtor envolvido deve ser um construtor constexpr e cada cláusula de cada inicializador cinta-ou-igual deve ser uma expressão constante
    Original:
    every base class and every non-static member must be initialized, either in the initializer_list or by brace-or-equal initializer. End every constructor involved must be a constexpr constructor and every clause of every brace-or-equal initializer must be a constant expression
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • cada conversão implícita envolvido deve ser uma expressão constante
    Original:
    every implicit conversion involved must be a constant expression
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

[editar] Palavras-chave

constexpr

[editar] Exemplo

Definição de uma função que calcula constexpr fatoriais e um tipo literal que se estende seqüências literais

Original:

Definition of a constexpr function which computes factorials and a literal type that extends string literals

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 <stdexcept>
 
// constexpr functions use recursion rather than iteration
constexpr int factorial(int n)
{
    return n <= 1 ? 1 : (n * factorial(n-1));
}
 
// literal class
class conststr {
    const char * p;
    std::size_t sz;
 public:
    template<std::size_t N>
    constexpr conststr(const char(&a)[N]) : p(a), sz(N-1) {}
    // constexpr functions signal errors by throwing exceptions from operator ?:
    constexpr char operator[](std::size_t n) {
        return n < sz ? p[n] : throw std::out_of_range("");
    }
    constexpr std::size_t size() { return sz; }
};
constexpr std::size_t countlower(conststr s, std::size_t n = 0,
                                             std::size_t c = 0) {
    return n == s.size() ? c :
           s[n] >= 'a' && s[n] <= 'z' ? countlower(s, n+1, c+1) :
           countlower(s, n+1, c);
}
 
// output function that requires a compile-time constant, for testing
template<int n> struct constN {
    constN() { std::cout << n << '\n'; }
};
 
int main()
{
    std::cout << "4! = " ;
    constN<factorial(4)> out1; // computed at compile time
 
    volatile int k = 8;
    std::cout << k << "! = " << factorial(k) << '\n'; // computed at run time
 
    std::cout << "Number of lowercase letters in \"Hello, world!\" is ";
    constN<countlower("Hello, world!")> out2; // implicitly converted to conststr
}

Saída:

4! = 24
8! = 40320
Number of lowercase letters in "Hello, world!" is 9