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

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

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

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

This exclusion applies to the parametersof the function, and if a parameter is a pointer to function or pointer to member function then to its parameters also, etc.§ 8.3.5© ISO/IEC 2011 – All rights reserved193ISO/IEC 14882:2011(E)typedef void F();F fv;F fv { }void fv() { }// OK: equivalent to void fv();// ill-formed// OK: definition of fv— end example ] A typedef of a function type whose declarator includes a cv-qualifier-seq shall be usedonly to declare the function type for a non-static member function, to declare the function type to which apointer to member refers, or to declare the top-level function type of another function typedef declaration.[ Example:typedef int FIC(int) const;FIC f;// ill-formed: does not declare a member functionstruct S {FIC f;// OK};FIC S::*pm = &S::f; // OK— end example ]11An identifier can optionally be provided as a parameter name; if present in a function definition (8.4), itnames a parameter (sometimes called “formal argument”).

[ Note: In particular, parameter names are alsooptional in function definitions and names used for a parameter in different declarations and the definitionof a function need not be the same. If a parameter name is present in a function declaration that is nota definition, it cannot be used outside of its function declarator because that is the extent of its potentialscope (3.3.4). — end note ]12[ Example: the declarationint i,*pi,f(),*fpi(int),(*pif)(const char*, const char*),(*fpif(int))(int);declares an integer i, a pointer pi to an integer, a function f taking no arguments and returning an integer,a function fpi taking an integer argument and returning a pointer to an integer, a pointer pif to a functionwhich takes two pointers to constant characters and returns an integer, a function fpif taking an integerargument and returning a pointer to a function that takes an integer argument and returns an integer.

Itis especially useful to compare fpi and pif. The binding of *fpi(int) is *(fpi(int)), so the declarationsuggests, and the same construction in an expression requires, the calling of a function fpi, and then usingindirection through the (pointer) result to yield an integer. In the declarator (*pif)(const char*, constchar*), the extra parentheses are necessary to indicate that indirection through a pointer to a function yieldsa function, which is then called. — end example ] [ Note: Typedefs and trailing-return-types are sometimesconvenient when the return type of a function is complex.

For example, the function fpif above could havebeen declaredtypedef int IFUNC(int);IFUNC* fpif(int);orauto fpif(int)->int(*)(int)A trailing-return-type is most useful for a type that would be more complicated to specify before thedeclarator-id:§ 8.3.5194© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)template <class T, class U> auto add(T t, U u) -> decltype(t + u);rather thantemplate <class T, class U> decltype((*(T*)0) + (*(U*)0)) add(T t, U u);— end note ]13A declarator-id or abstract-declarator containing an ellipsis shall only be used in a parameter-declaration.Such a parameter-declaration is a parameter pack (14.5.3). When it is part of a parameter-declaration-clause,the parameter pack is a function parameter pack (14.5.3).

[ Note: Otherwise, the parameter-declaration ispart of a template-parameter-list and the parameter pack is a template parameter pack; see 14.1. — endnote ] A function parameter pack is a pack expansion (14.5.3). [ Example:template<typename... T> void f(T (* ...t)(int, int));int add(int, int);float subtract(int, int);void g() {f(add, subtract);}— end example ]14There is a syntactic ambiguity when an ellipsis occurs at the end of a parameter-declaration-clause withouta preceding comma. In this case, the ellipsis is parsed as part of the abstract-declarator if the type of theparameter names a template parameter pack that has not been expanded; otherwise, it is parsed as part ofthe parameter-declaration-clause.1008.3.6Default arguments[dcl.fct.default]1If an initializer-clause is specified in a parameter-declaration this initializer-clause is used as a defaultargument. Default arguments will be used in calls where trailing arguments are missing.2[ Example: the declarationvoid point(int = 3, int = 4);declares a function that can be called with zero, one, or two arguments of type int.

It can be called in anyof these ways:point(1,2);point(1);point();The last two calls are equivalent to point(1,4) and point(3,4), respectively. — end example ]3A default argument shall be specified only in the parameter-declaration-clause of a function declaration orin a template-parameter (14.1); in the latter case, the initializer-clause shall be an assignment-expression.A default argument shall not be specified for a parameter pack.

If it is specified in a parameter-declarationclause, it shall not occur within a declarator or abstract-declarator of a parameter-declaration.101100) One can explicitly disambiguate the parse either by introducing a comma (so the ellipsis will be parsed as part of theparameter-declaration-clause) or by introducing a name for the parameter (so the ellipsis will be parsed as part of the declaratorid).101) This means that default arguments cannot appear, for example, in declarations of pointers to functions, references tofunctions, or typedef declarations.§ 8.3.6© ISO/IEC 2011 – All rights reserved195ISO/IEC 14882:2011(E)4For non-template functions, default arguments can be added in later declarations of a function in thesame scope. Declarations in different scopes have completely distinct sets of default arguments.

That is,declarations in inner scopes do not acquire default arguments from declarations in outer scopes, and viceversa. In a given function declaration, each parameter subsequent to a parameter with a default argumentshall have a default argument supplied in this or a previous declaration or shall be a function parameter pack.A default argument shall not be redefined by a later declaration (not even to the same value).

[ Example:void g(int = 0, ...);void f(int, int);void f(int, int = 7);void h() {f(3);void f(int = 1, int);}void m() {void f(int, int);f(4);void f(int, int = 5);f(4);void f(int, int = 5);}void n() {f(6);}// OK, ellipsis is not a parameter so it can follow// a parameter with a default argument// OK, calls f(3, 7)// error: does not use default// from surrounding scope////////////has no defaultserror: wrong number of argumentsOKOK, calls f(4, 5);error: cannot redefine, even tosame value// OK, calls f(6, 7)— end example ] For a given inline function defined in different translation units, the accumulated sets ofdefault arguments at the end of the translation units shall be the same; see 3.2.

If a friend declaration specifiesa default argument expression, that declaration shall be a definition and shall be the only declaration of thefunction or function template in the translation unit.5A default argument is implicitly converted (Clause 4) to the parameter type. The default argument hasthe same semantic constraints as the initializer in a declaration of a variable of the parameter type, usingthe copy-initialization semantics (8.5).

The names in the default argument are bound, and the semanticconstraints are checked, at the point where the default argument appears. Name lookup and checking ofsemantic constraints for default arguments in function templates and in member functions of class templatesare performed as described in 14.7.1. [ Example: in the following code, g will be called with the value f(2):int a = 1;int f(int);int g(int x = f(a));void h() {a = 2;{int a = 3;g();}}// default argument: f(::a)// g(f(::a))— end example ] [ Note: In member function declarations, names in default arguments are looked up asdescribed in 3.4.1.

Access checking applies to names in default arguments as described in Clause 11. — endnote ]§ 8.3.6196© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)6Except for member functions of class templates, the default arguments in a member function definition thatappears outside of the class definition are added to the set of default arguments provided by the memberfunction declaration in the class definition.

Default arguments for a member function of a class templateshall be specified on the initial declaration of the member function within the class template. [ Example:class C {void f(int i = 3);void g(int i, int j = 99);};void C::f(int i = 3) {}void C::g(int i = 88, int j) {}////////error: default argument alreadyspecified in class scopein this translation unit,C::g can be called with no argument— end example ]7Local variables shall not be used in a default argument.

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

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

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

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