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

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

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

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

Classtemplates are instantiated as necessary to determine if a qualified name is a type-name. Disambiguationprecedes parsing, and a statement disambiguated as a declaration may be an ill-formed declaration. If,during parsing, a name in a template parameter is bound differently than it would be bound during a trialparse, the program is ill-formed. No diagnostic is required. [ Note: This can occur only when the name isdeclared earlier in the declaration. — end note ] [ Example:struct T1 {T1 operator()(int x) { return T1(x); }int operator=(int x) { return x; }T1(int) { }};struct T2 { T2(int){ } };int a, (*(*b)(T2))(int), c, d;void f() {// disambiguation requires this to be parsed as a declaration:T1(a) = 3,T2(4),// T2 will be declared as(*(*b)(T2(c)))(int(d));// a variable of type T1// but this will not allow// the last part of the// declaration to parse// properly since it depends// on T2 being a type-name}— end example ]§ 6.8© ISO/IEC 2011 – All rights reserved139ISO/IEC 14882:2011(E)71Declarations[dcl.dcl]Declarations generally specify how names are to be interpreted.

Declarations have the formdeclaration-seq:declarationdeclaration-seq declarationdeclaration:block-declarationfunction-definitiontemplate-declarationexplicit-instantiationexplicit-specializationlinkage-specificationnamespace-definitionempty-declarationattribute-declarationblock-declaration:simple-declarationasm-definitionnamespace-alias-definitionusing-declarationusing-directivestatic_assert-declarationalias-declarationopaque-enum-declarationalias-declaration:using identifier attribute-specifier-seqopt = type-id ;simple-declaration:decl-specifier-seqopt init-declarator-listopt ;attribute-specifier-seq decl-specifier-seqopt init-declarator-list ;static_assert-declaration:static_assert ( constant-expression , string-literal ) ;empty-declaration:;attribute-declaration:attribute-specifier-seq ;[ Note: asm-definitions are described in 7.4, and linkage-specifications are described in 7.5.

Functiondefinitions are described in 8.4 and template-declarations are described in Clause 14. Namespace-definitionsare described in 7.3.1, using-declarations are described in 7.3.3 and using-directives are described in 7.3.4.— end note ]The simple-declarationattribute-specifier-seqopt decl-specifier-seqopt init-declarator-listopt ;is divided into three parts. Attributes are described in 7.6. decl-specifiers, the principal components of adecl-specifier-seq, are described in 7.1. declarators, the components of an init-declarator-list, are describedin Clause 8. The attribute-specifier-seq in a simple-declaration appertains to each of the entities declared by140© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)the declarators of the init-declarator-list. [ Note: In the declaration for an entity, attributes appertainingto that entity may appear at the start of the declaration and after the declarator-id for that declaration.— end note ] [ Example:[[noreturn]] void f [[noreturn]] (); // OK— end example ]Except where otherwise specified, the meaning of an attribute-declaration is implementation-defined.2A declaration occurs in a scope (3.3); the scope rules are summarized in 3.4.

A declaration that declares afunction or defines a class, namespace, template, or function also has one or more scopes nested within it.These nested scopes, in turn, can have declarations nested within them. Unless otherwise stated, utterancesin Clause 7 about components in, of, or contained by a declaration or subcomponent thereof refer only tothose components of the declaration that are not nested within scopes nested within the declaration.3In a simple-declaration, the optional init-declarator-list can be omitted only when declaring a class (Clause 9)or enumeration (7.2), that is, when the decl-specifier-seq contains either a class-specifier, an elaboratedtype-specifier with a class-key (9.1), or an enum-specifier.

In these cases and whenever a class-specifier orenum-specifier is present in the decl-specifier-seq, the identifiers in these specifiers are among the names beingdeclared by the declaration (as class-names, enum-names, or enumerators, depending on the syntax). In suchcases, and except for the declaration of an unnamed bit-field (9.6), the decl-specifier-seq shall introduce oneor more names into the program, or shall redeclare a name introduced by a previous declaration.

[ Example:enum { };typedef class { };// ill-formed// ill-formed— end example ]4In a static_assert-declaration the constant-expression shall be a constant expression (5.19) that can becontextually converted to bool (Clause 4). If the value of the expression when so converted is true, thedeclaration has no effect. Otherwise, the program is ill-formed, and the resulting diagnostic message (1.4)shall include the text of the string-literal, except that characters not in the basic source character set (2.3)are not required to appear in the diagnostic message.

[ Example:static_assert(sizeof(long) >= 8, "64-bit code generation required for this library.");— end example ]5An empty-declaration has no effect.6Each init-declarator in the init-declarator-list contains exactly one declarator-id, which is the name declaredby that init-declarator and hence one of the names declared by the declaration.

The type-specifiers (7.1.6)in the decl-specifier-seq and the recursive declarator structure of the init-declarator describe a type (8.3),which is then associated with the name being declared by the init-declarator.7If the decl-specifier-seq contains the typedef specifier, the declaration is called a typedef declaration and thename of each init-declarator is declared to be a typedef-name, synonymous with its associated type (7.1.3).If the decl-specifier-seq contains no typedef specifier, the declaration is called a function declaration if thetype associated with the name is a function type (8.3.5) and an object declaration otherwise.8Syntactic components beyond those found in the general form of declaration are added to a function declaration to make a function-definition.

An object declaration, however, is also a definition unless it containsthe extern specifier and has no initializer (3.1). A definition causes the appropriate amount of storage tobe reserved and any appropriate initialization (8.5) to be done.© ISO/IEC 2011 – All rights reserved141ISO/IEC 14882:2011(E)9Only in function declarations for constructors, destructors, and type conversions can the decl-specifier-seqbe omitted.897.11Specifiers[dcl.spec]The specifiers that can be used in a declaration aredecl-specifier:storage-class-specifiertype-specifierfunction-specifierfriendtypedefconstexprdecl-specifier-seq:decl-specifier attribute-specifier-seqoptdecl-specifier decl-specifier-seqThe optional attribute-specifier-seq in a decl-specifier-seq appertains to the type determined by the precedingdecl-specifiers (8.3).

The attribute-specifier-seq affects the type only for the declaration it appears in, notother declarations involving the same type.2If a type-name is encountered while parsing a decl-specifier-seq, it is interpreted as part of the decl-specifierseq if and only if there is no previous type-specifier other than a cv-qualifier in the decl-specifier-seq. Thesequence shall be self-consistent as described below. [ Example:typedef char* Pc;static Pc;// error: name missingHere, the declaration static Pc is ill-formed because no name was specified for the static variable of type Pc.To get a variable called Pc, a type-specifier (other than const or volatile) has to be present to indicate thatthe typedef-name Pc is the name being (re)declared, rather than being part of the decl-specifier sequence.For another example,void f(const Pc);void g(const int Pc);// void f(char* const) (not const char*)// void g(const int)— end example ]3[ Note: Since signed, unsigned, long, and short by default imply int, a type-name appearing after one ofthose specifiers is treated as the name being (re)declared.

[ Example:void h(unsigned Pc);void k(unsigned int Pc);// void h(unsigned int)// void k(unsigned int)— end example ] — end note ]7.1.11Storage class specifiers[dcl.stc]The storage class specifiers arestorage-class-specifier:registerstaticthread_localexternmutable89) The “implicit int” rule of C is no longer supported.§ 7.1.1142© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)At most one storage-class-specifier shall appear in a given decl-specifier-seq, except that thread_local mayappear with static or extern. If thread_local appears in any declaration of a variable it shall be presentin all declarations of that entity. If a storage-class-specifier appears in a decl-specifier-seq, there can beno typedef specifier in the same decl-specifier-seq and the init-declarator-list of the declaration shall notbe empty (except for an anonymous union declared in a named namespace or in the global namespace,which shall be declared static (9.5)).

The storage-class-specifier applies to the name declared by eachinit-declarator in the list and not to any names declared by other specifiers. A storage-class-specifier shallnot be specified in an explicit specialization (14.7.3) or an explicit instantiation (14.7.2) directive.2The register specifier shall be applied only to names of variables declared in a block (6.3) or to functionparameters (8.4).

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

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

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

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