Главная » Просмотр файлов » Стандарт C++ 11

Стандарт C++ 11 (1119564), страница 48

Файл №1119564 Стандарт C++ 11 (Стандарт C++ 11) 48 страницаСтандарт C++ 11 (1119564) страница 482019-05-09СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 48)

[ Note: An explicit specialization can differ from the template declaration with respect to theconstexpr specifier. — end note ] [ Note: Function parameters cannot be declared constexpr. — end note ][ Example:constexpr int square(int x);constexpr int bufsz = 1024;constexpr struct pixel {int x;int y;constexpr pixel(int);};constexpr pixel::pixel(int a): x(square(a)), y(square(a)){ }constexpr pixel small(2);constexpr int square(int x) {return x * x;}constexpr pixel large(4);// OK: declaration// OK: definition// error: pixel is a type// OK: declaration// OK: definition// error: square not defined, so small(2)// not constant (5.19) so constexpr not satisfied// OK: definition// OK: square defined§ 7.1.5© ISO/IEC 2011 – All rights reserved147ISO/IEC 14882:2011(E)int next(constexpr int x) {return x + 1;}extern constexpr int memsz;// error: not for parameters// error: not a definition— end example ]23A constexpr specifier used in the declaration of a function that is not a constructor declares that functionto be a constexpr function.

Similarly, a constexpr specifier used in a constructor declaration declares thatconstructor to be a constexpr constructor. constexpr functions and constexpr constructors are implicitlyinline (7.1.2).The definition of a constexpr function shall satisfy the following constraints:— it shall not be virtual (10.3);— its return type shall be a literal type;— each of its parameter types shall be a literal type;— its function-body shall be = delete, = default, or a compound-statement that contains only— null statements,— static_assert-declarations— typedef declarations and alias-declarations that do not define classes or enumerations,— using-declarations,— using-directives,— and exactly one return statement;— every constructor call and implicit conversion used in initializing the return value (6.6.3, 8.5) shall beone of those allowed in a constant expression (5.19).[ Example:constexpr int square(int x){ return x * x; }constexpr long long_max(){ return 2147483647; }constexpr int abs(int x){ return x < 0 ? -x : x; }constexpr void f(int x){ /∗ ...

∗/ }constexpr int prev(int x){ return --x; }constexpr int g(int x, int n) {int r = 1;while (--n > 0) r *= x;return r;}// OK// OK// OK// error: return type is void// error: use of decrement// error: body not just “return expr”— end example ]4In a definition of a constexpr constructor, each of the parameter types shall be a literal type. In addition,either its function-body shall be = delete or = default or it shall satisfy the following constraints:— the class shall not have any virtual base classes;§ 7.1.5148© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)— its function-body shall not be a function-try-block;— the compound-statement of its function-body shall contain only— null statements,— static_assert-declarations— typedef declarations and alias-declarations that do not define classes or enumerations,— using-declarations,— and using-directives;— every non-static data member and base class sub-object shall be initialized (12.6.2);— every constructor involved in initializing non-static data members and base class sub-objects shall bea constexpr constructor;— every assignment-expression that is an initializer-clause appearing directly or indirectly within a braceor-equal-initializer for a non-static data member that is not named by a mem-initializer-id shall be aconstant expression; and— every implicit conversion used in converting a constructor argument to the corresponding parametertype and converting a full-expression to the corresponding member type shall be one of those allowedin a constant expression.[ Example:struct Length {explicit constexpr Length(int i = 0) : val(i) { }private:int val;};— end example ]5Function invocation substitution for a call of a constexpr function or of a constexpr constructor meansimplicitly converting each argument to the corresponding parameter type as if by copy-initialization,91substituting that converted expression for each use of the corresponding parameter in the function-body,and, for constexpr functions, implicitly converting the resulting returned expression or braced-init-list tothe return type of the function as if by copy-initialization.

Such substitution does not change the meaning.[ Example:constexprconstexprconstexprconstexprconstexprintintintintintf(voidf(...)g1() {g2(intg3(int*) { return 0; }{ return 1; }return f(0); }n) { return f(n); }n) { return f(n*0); }namespace N {constexpr int c = 5;constexpr int h() { return c; }}constexpr int c = 0;constexpr int g4() { return N::h(); }// calls f(void *)// calls f(...) even for n == 0// calls f(...)// value is 5, c is not looked up again after the substitution91) The resulting converted value will include an lvalue-to-rvalue conversion (4.1) if the corresponding copy-initializationrequires one.§ 7.1.5© ISO/IEC 2011 – All rights reserved149ISO/IEC 14882:2011(E)— end example ]For a constexpr function, if no function argument values exist such that the function invocation substitution would produce a constant expression (5.19), the program is ill-formed; no diagnostic required. Fora constexpr constructor, if no argument values exist such that after function invocation substitution, every constructor call and full-expression in the mem-initializers would be a constant expression (includingconversions), the program is ill-formed; no diagnostic required.

[ Example:constexpr int f(bool b){ return b ? throw 0 : 0; }constexpr int f() { throw 0; }struct B {constexpr B(int x) : i(0) { }int i;};// OK// ill-formed, no diagnostic required// x is unusedint global;struct D : B {constexpr D() : B(global) { }// ill-formed, no diagnostic required// lvalue-to-rvalue conversion on non-constant global};— end example ]6If the instantiated template specialization of a constexpr function template or member function of a classtemplate would fail to satisfy the requirements for a constexpr function or constexpr constructor, thatspecialization is not a constexpr function or constexpr constructor.

[ Note: If the function is a memberfunction it will still be const as described below. — end note ] If no specialization of the template wouldyield a constexpr function or constexpr constructor, the program is ill-formed; no diagnostic required.7A call to a constexpr function produces the same result as a call to an equivalent non-constexpr functionin all respects except that a call to a constexpr function can appear in a constant expression.8A constexpr specifier for a non-static member function that is not a constructor declares that memberfunction to be const (9.3.1). [ Note: The constexpr specifier has no other effect on the function type.

—end note ] The keyword const is ignored if it appears in the cv-qualifier-seq of the function declarator ofthe declaration of such a member function. The class of which that function is a member shall be a literaltype (3.9). [ Example:class debug_flag {public:explicit debug_flag(bool);constexpr bool is_on();// error: debug_flag not// literal typeprivate:bool flag;};constexpr int bar(int x, int y) // OK{ return x + y + x*y; }// ...int bar(int x, int y)// error: redefinition of bar{ return x * 2 + 3 * y; }— end example ]§ 7.1.5150© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)9A constexpr specifier used in an object declaration declares the object as const.

Such an object shall haveliteral type and shall be initialized. If it is initialized by a constructor call, that call shall be a constantexpression (5.19). Otherwise, or if a constexpr specifier is used in a reference declaration, every fullexpression that appears in its initializer shall be a constant expression. Each implicit conversion used inconverting the initializer expressions and each constructor call used for the initialization shall be one of thoseallowed in a constant expression (5.19).

[ Example:struct pixel {int x, y;};constexpr pixel ur = { 1294, 1024 };// OKconstexpr pixel origin;// error: initializer missing— end example ]7.1.61Type specifiers[dcl.type]The type-specifiers aretype-specifier:trailing-type-specifierclass-specifierenum-specifiertrailing-type-specifier:simple-type-specifierelaborated-type-specifiertypename-specifiercv-qualifiertype-specifier-seq:type-specifier attribute-specifier-seqopttype-specifier type-specifier-seqtrailing-type-specifier-seq:trailing-type-specifier attribute-specifier-seqopttrailing-type-specifier trailing-type-specifier-seqThe optional attribute-specifier-seq in a type-specifier-seq or a trailing-type-specifier-seq appertains to thetype denoted by the preceding type-specifiers (8.3). The attribute-specifier-seq affects the type only for thedeclaration it appears in, not other declarations involving the same type.2As a general rule, at most one type-specifier is allowed in the complete decl-specifier-seq of a declaration orin a type-specifier-seq or trailing-type-specifier-seq.

The only exceptions to this rule are the following:— const can be combined with any type specifier except itself.— volatile can be combined with any type specifier except itself.— signed or unsigned can be combined with char, long, short, or int.— short or long can be combined with int.— long can be combined with double.— long can be combined with long.§ 7.1.6© ISO/IEC 2011 – All rights reserved151ISO/IEC 14882:2011(E)3At least one type-specifier that is not a cv-qualifier is required in a declaration unless it declares a constructor,destructor or conversion function.92 A type-specifier-seq shall not define a class or enumeration unless itappears in the type-id of an alias-declaration (7.1.3) that is not the declaration of a template-declaration.4[ Note: enum-specifiers, class-specifiers, and typename-specifiers are discussed in 7.2, 9, and 14.6, respectively.

The remaining type-specifiers are discussed in the rest of this section. — end note ]7.1.6.1The cv-qualifiers[dcl.type.cv]1There are two cv-qualifiers, const and volatile. If a cv-qualifier appears in a decl-specifier-seq, the initdeclarator-list of the declaration shall not be empty. [ Note: 3.9.3 and 8.3.5 describe how cv-qualifiers affectobject and function types. — end note ] Redundant cv-qualifications are ignored. [ Note: For example, thesecould be introduced by typedefs. — end note ]2[ Note: Declaring a variable const can affect its linkage (7.1.1) and its usability in constant expressions (5.19).As described in 8.5, the definition of an object or subobject of const-qualified type must specify an initializeror be subject to default-initialization.

Характеристики

Тип файла
PDF-файл
Размер
14,26 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов учебной работы

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6381
Авторов
на СтудИзбе
308
Средний доход
с одного платного файла
Обучение Подробнее