constexpr specifier (начиная с C++11)
Материал из 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. |
constexpr- указывает, что значение переменной или функции можно вычислить во время компиляцииOriginal:constexpr- specifies that the value of a variable or function can be computed at compile timeThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
[править] Объяснение
constexpr спецификатор заявляет, что это возможно оценить значение функции или переменной во время компиляции, затем они могут быть использованы, где только время компиляции постоянные выражения не допускается. constexpr подразумевает 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 постоянные выражения 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.
You can help to correct and verify the translation. Click here for instructions.
'constexpr переменных' должны удовлетворять следующим требованиям:
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.
You can help to correct and verify the translation. Click here for instructions.
- она должна быть немедленно построены или присвоенное значение.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. - Конструктор параметры или значение, которое присваивается должны содержать только буквенные значения,
constexprпеременных и функций.Original:the constructor parameters or the value to be assigned must contain only literal values,constexprvariables 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конструктор. В случае явного конструктора, это должно быть указано constexpr.Original:the constructor used to construct the object (either implicit or explicit) must satisfy the requirements ofconstexprconstructor. 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 функции' должны удовлетворять следующим требованиям:
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.
You can help to correct and verify the translation. Click here for instructions.
- она не должна быть виртуальнойOriginal:it must not be virtualThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - возвращаемый тип должен быть
LiteralTypeOriginal:its return type must beLiteralTypeThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Каждый из его параметров должны быть буквальным типаOriginal:each of its parameters must be literal typeThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Тело функции должны быть либо удалены или дефолт или содержать только следующие: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.
- нулевой отчетностиOriginal:null statementsThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - static_assert декларацийOriginal:static_assert declarationsThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
typedefзаявлений и деклараций псевдонима, которые не определяют классы или перечисленияOriginal:typedefdeclarations and псевдонима declarations that do not define classes or enumerationsThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - использование декларацийOriginal:using declarationsThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - с помощью директивOriginal:using directivesThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - ровно один
returnзаявление, которое содержит только буквенные значения,constexprпеременных и функций.Original:exactly onereturnstatement that contains only literal values,constexprvariables 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 конструктор' должны удовлетворять следующим требованиям:
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.
You can help to correct and verify the translation. Click here for instructions.
- Каждый из его параметров должны быть буквальным типаOriginal:each of its parameters must be literal typeThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Класс должен иметь не виртуальные базовые классыOriginal:the class must have no virtual base classesThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Конструктор тело должно быть либо исключить, либо дефолт, либо содержат лишь следующее: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.
- нулевой отчетностиOriginal:null statementsThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - static_assert декларацийOriginal:static_assert declarationsThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
typedefзаявлений и деклараций псевдонима, которые не определяют классы или перечисленияOriginal:typedefdeclarations and псевдонима declarations that do not define classes or enumerationsThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - использование декларацийOriginal:using declarationsThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - с помощью директивOriginal:using directivesThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
- Конструктор не должен иметь функции-блока проверкиOriginal:the constructor must not have a function-try blockThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - каждый базовый класс, и каждый не статические члены должны инициализироваться, либо в
initializer_listили фигурную скобку или равно инициализатор. Конец каждого конструктора участие должно быть конструктором КонстВыраж и каждый пункт каждого скобки или равно инициализаторе должно быть постоянным выражениемOriginal:every base class and every non-static member must be initialized, either in theinitializer_listor 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 expressionThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - каждый неявного преобразования участие должно быть постоянным выражениемOriginal:every implicit conversion involved must be a constant expressionThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
[править] Ключевые слова
[править] Пример
Определение КонстВыраж функцию, которая вычисляет факториал и тип литерала, который расширяет строковые литералы
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.
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 }
Вывод:
4! = 24 8! = 40320 Number of lowercase letters in "Hello, world!" is 9