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

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

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

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

The implicit conversion sequence is the one required to convertthe argument expression to a prvalue of the type of the parameter. [ Note: When the parameter has a classtype, this is a conceptual conversion defined for the purposes of Clause 13; the actual initialization is definedin terms of constructors and is not a conversion. — end note ] Any difference in top-level cv-qualification issubsumed by the initialization itself and does not constitute a conversion. [ Example: a parameter of type Acan be initialized from an argument of type const A. The implicit conversion sequence for that case is theidentity sequence; it contains no “conversion” from const A to A. — end example ] When the parameter hasa class type and the argument expression has the same type, the implicit conversion sequence is an identityconversion.

When the parameter has a class type and the argument expression has a derived class type,the implicit conversion sequence is a derived-to-base Conversion from the derived class to the base class.[ Note: There is no such standard conversion; this derived-to-base Conversion exists only in the description ofimplicit conversion sequences. — end note ] A derived-to-base Conversion has Conversion rank (13.3.3.1.1).7In all contexts, when converting to the implicit object parameter or when converting to the left operand ofan assignment operation only standard conversion sequences that create no temporary object for the resultare allowed.8If no conversions are required to match an argument to a parameter type, the implicit conversion sequenceis the standard conversion sequence consisting of the identity conversion (13.3.3.1.1).9If no sequence of conversions can be found to convert an argument to a parameter type or the conversion isotherwise ill-formed, an implicit conversion sequence cannot be formed.§ 13.3.3.1© ISO/IEC 2011 – All rights reserved303ISO/IEC 14882:2011(E)10If several different sequences of conversions exist that each convert the argument to the parameter type, theimplicit conversion sequence associated with the parameter is defined to be the unique conversion sequencedesignated the ambiguous conversion sequence.

For the purpose of ranking implicit conversion sequencesas described in 13.3.3.2, the ambiguous conversion sequence is treated as a user-defined sequence that isindistinguishable from any other user-defined conversion sequence134 . If a function that uses the ambiguousconversion sequence is selected as the best viable function, the call will be ill-formed because the conversionof one of the arguments in the call is ambiguous.11The three forms of implicit conversion sequences mentioned above are defined in the following subclauses.13.3.3.1.1Standard conversion sequences[over.ics.scs]1Table 12 summarizes the conversions defined in Clause 4 and partitions them into four disjoint categories:Lvalue Transformation, Qualification Adjustment, Promotion, and Conversion.

[ Note: These categories areorthogonal with respect to value category, cv-qualification, and data representation: the Lvalue Transformations do not change the cv-qualification or data representation of the type; the Qualification Adjustmentsdo not change the value category or data representation of the type; and the Promotions and Conversionsdo not change the value category or cv-qualification of the type. — end note ]2[ Note: As described in Clause 4, a standard conversion sequence is either the Identity conversion by itself(that is, no conversion) or consists of one to three conversions from the other four categories. At most oneconversion from each category is allowed in a single standard conversion sequence.

If there are two or moreconversions in the sequence, the conversions are applied in the canonical order: Lvalue Transformation,Promotion or Conversion, Qualification Adjustment. — end note ]3Each conversion in Table 12 also has an associated rank (Exact Match, Promotion, or Conversion). These areused to rank standard conversion sequences (13.3.3.2).

The rank of a conversion sequence is determined byconsidering the rank of each conversion in the sequence and the rank of any reference binding (13.3.3.1.4). Ifany of those has Conversion rank, the sequence has Conversion rank; otherwise, if any of those has Promotionrank, the sequence has Promotion rank; otherwise, the sequence has Exact Match rank.13.3.3.1.21User-defined conversion sequences[over.ics.user]A user-defined conversion sequence consists of an initial standard conversion sequence followed by a userdefined conversion (12.3) followed by a second standard conversion sequence. If the user-defined conversionis specified by a constructor (12.3.1), the initial standard conversion sequence converts the source type to the134) The ambiguous conversion sequence is ranked with user-defined conversion sequences because multiple conversion sequencesfor an argument can exist only if they involve different user-defined conversions.

The ambiguous conversion sequence is indistinguishable from any other user-defined conversion sequence because it represents at least two user-defined conversion sequences,each with a different user-defined conversion, and any other user-defined conversion sequence must be indistinguishable fromat least one of them.This rule prevents a function from becoming non-viable because of an ambiguous conversion sequence for one of its parameters.Consider this example,class B;class A { A (B&);};class B { operator A (); };class C { C (B&); };void f(A) { }void f(C) { }B b;f(b);// ambiguous because b → C via constructor and// b → A via constructor or conversion function.If it were not for this rule, f(A) would be eliminated as a viable function for the call f(b) causing overload resolution toselect f(C) as the function to call even though it is not clearly the best choice.

On the other hand, if an f(B) were to bedeclared then f(b) would resolve to that f(B) because the exact match with f(B) is better than any of the sequences requiredto match f(A).§ 13.3.3.1.2304© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)Table 12 — ConversionsConversionNo conversions requiredLvalue-to-rvalue conversionArray-to-pointer conversionFunction-to-pointer conversionQualification conversionsIntegral promotionsFloating point promotionIntegral conversionsFloating point conversionsFloating-integral conversionsPointer conversionsPointer to member conversionsBoolean conversionsCategoryIdentityRankLvalue TransformationExact MatchQualification AdjustmentPromotionPromotionConversionConversionSubclause4.14.24.34.44.54.64.74.84.94.104.114.12type required by the argument of the constructor.

If the user-defined conversion is specified by a conversionfunction (12.3.2), the initial standard conversion sequence converts the source type to the implicit objectparameter of the conversion function.2The second standard conversion sequence converts the result of the user-defined conversion to the target typefor the sequence. Since an implicit conversion sequence is an initialization, the special rules for initializationby user-defined conversion apply when selecting the best user-defined conversion for a user-defined conversionsequence (see 13.3.3 and 13.3.3.1).3If the user-defined conversion is specified by a specialization of a conversion function template, the secondstandard conversion sequence shall have exact match rank.4A conversion of an expression of class type to the same class type is given Exact Match rank, and a conversionof an expression of class type to a base class of that type is given Conversion rank, in spite of the fact thata copy/move constructor (i.e., a user-defined conversion function) is called for those cases.13.3.3.1.31[over.ics.ellipsis]An ellipsis conversion sequence occurs when an argument in a function call is matched with the ellipsisparameter specification of the function called (see 5.2.2).13.3.3.1.41Ellipsis conversion sequencesReference binding[over.ics.ref ]When a parameter of reference type binds directly (8.5.3) to an argument expression, the implicit conversionsequence is the identity conversion, unless the argument expression has a type that is a derived class of theparameter type, in which case the implicit conversion sequence is a derived-to-base Conversion (13.3.3.1).[ Example:struct A {};struct B : public A {} b;int f(A&);int f(B&);int i = f(b);// calls f(B&), an exact match, rather than// f(A&), a conversion— end example ] If the parameter binds directly to the result of applying a conversion function to theargument expression, the implicit conversion sequence is a user-defined conversion sequence (13.3.3.1.2),§ 13.3.3.1.4© ISO/IEC 2011 – All rights reserved305ISO/IEC 14882:2011(E)with the second standard conversion sequence either an identity conversion or, if the conversion functionreturns an entity of a type that is a derived class of the parameter type, a derived-to-base Conversion.2When a parameter of reference type is not bound directly to an argument expression, the conversion sequenceis the one required to convert the argument expression to the underlying type of the reference accordingto 13.3.3.1.

Conceptually, this conversion sequence corresponds to copy-initializing a temporary of theunderlying type with the argument expression. Any difference in top-level cv-qualification is subsumed bythe initialization itself and does not constitute a conversion.3Except for an implicit object parameter, for which see 13.3.1, a standard conversion sequence cannot beformed if it requires binding an lvalue reference other than a reference to a non-volatile const type toan rvalue or binding an rvalue reference to an lvalue other than a function lvalue. [ Note: This means,for example, that a candidate function cannot be a viable function if it has a non-const lvalue referenceparameter (other than the implicit object parameter) and the corresponding argument is a temporary orwould require one to be created to initialize the lvalue reference (see 8.5.3).

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

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

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

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