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

Стандарт C++ 98 (1119566), страница 77

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

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

If a substitution in a template parameter or in thefunction type of the function template results in an invalid type, type deduction fails. [Note: The equivalent substitution in exception specifications is done only when the function is instantiated, at whichpoint a program is ill-formed if the substitution results in an invalid type.] Type deduction may fail forthe following reasons:— Attempting to create an array with an element type that is void, a function type, or a reference type,or attempting to create an array with a size that is zero or negative.

[Example:280© ISO/IECISO/IEC 14882:1998(E)14 Templates14.8.2 Template argument deductiontemplate <class T> int f(T[5]);int I = f<int>(0);int j = f<void>(0);// invalid array]— Attempting to use a type that is not a class type in a qualified name. [Example:template <class T> int f(typename T::B*);int i = f<int>(0);]— Attempting to use a type in the qualifier portion of a qualified name that names a type when thattype does not contain the specified member, or if the specified member is not a type where a type isrequired. [Example:template <class T> int f(typename T::B*);struct A {};struct C { int B; };int i = f<A>(0);int j = f<C>(0);]— Attempting to create a pointer to reference type.— Attempting to create a reference to a reference type or a reference to void.— Attempting to create "pointer to member of T" when T is not a class type.

[Example:template <class T> int f(int T::*);int i = f<int>(0);]— Attempting to perform an invalid conversion in either a template argument expression, or an expression used in the function declaration. [Example:template <class T, T*> int f(int);int i2 = f<int,1>(0);// can’t conv 1 to int*]— Attempting to create a function type in which a parameter has a type of void.— Attempting to create a cv-qualified function type.3After this substitution is performed, the function parameter type adjustments described in 8.3.5 are performed.

[Example: A parameter type of “void ()(const int, int[5])” becomes“void(*)(int,int*)”. ] [Note: A top-level qualifier in a function parameter declaration does notaffect the function type but still affects the type of the function parameter variable within the function.—end note] [Example:281ISO/IEC 14882:1998(E)14.8.2 Template argument deduction© ISO/IEC14 Templatestemplate <class T> void f(T t);template <class X> void g(const X x);template <class Z> void h(Z, Z*);int main(){// #1: function type is f(int), t is nonconstf<int>(1);// #2: function type is f(int), t is constf<const int>(1);// #3: function type is g(int), x is constg<int>(1);// #4: function type is g(int), x is constg<const int>(1);// #5: function type is h(int, const int*)h<const int>(1,0);}—end example] [Note: f<int>(1) and f<const int>(1) call distinct functions even though bothof the functions called have the same function type.

—end note]4The resulting substituted and adjusted function type is used as the type of the function template for templateargument deduction. When all template arguments have been deduced, all uses of template parameters innondeduced contexts are replaced with the corresponding deduced argument values. If the substitutionresults in an invalid type, as described above, type deduction fails.5Except as described above, the use of an invalid value shall not cause type deduction to fail. [Example: Inthe following example 1000 is converted to signed char and results in an implementation-definedvalue as specified in (4.7).

In other words, both templates are considered even though 1000, when converted to signed char, results in an implementation-defined value.templatetemplateint i1 =int i2 =<int> int f(int);<signed char> int f(int);f<1>(0);// ambiguousf<1000>(0);// ambiguous—end example]14.8.2.1 Deducing template arguments from a function call[temp.deduct.call]1Template argument deduction is done by comparing each function template parameter type (call it P) withthe type of the corresponding argument of the call (call it A) as described below.2If P is not a reference type:— If A is an array type, the pointer type produced by the array-to-pointer standard conversion (4.2) is usedin place of A for type deduction; otherwise,— If A is a function type, the pointer type produced by the function-to-pointer standard conversion (4.3) isused in place of A for type deduction; otherwise,— If A is a cv-qualified type, the top level cv-qualifiers of A’s type are ignored for type deduction.If P is a cv-qualified type, the top level cv-qualifiers of P’s type are ignored for type deduction.

If P is areference type, the type referred to by P is used for type deduction.3In general, the deduction process attempts to find template argument values that will make the deduced Aidentical to A (after the type A is transformed as described above). However, there are three cases thatallow a difference:282© ISO/IEC14 TemplatesISO/IEC 14882:1998(E)14.8.2.1 Deducing template arguments from a function call— If the original P is a reference type, the deduced A (i.e., the type referred to by the reference) can bemore cv-qualified than A.— A can be another pointer or pointer to member type that can be converted to the deduced A via a qualification conversion (4.4).— If P is a class, and P has the form template-id, then A can be a derived class of the deduced A.

Likewise, if P is a pointer to a class of the form template-id, A can be a pointer to a derived class pointed toby the deduced A.These alternatives are considered only if type deduction would otherwise fail. If they yield more than onepossible deduced A, the type deduction fails. [Note: if a template-parameter is not used in any of the function parameters of a function template, or is used only in a non-deduced context, its correspondingtemplate-argument cannot be deduced from a function call and the template-argument must be explicitlyspecified. ]14.8.2.2 Deducing template arguments taking the address of a functiontemplate1[temp.deduct.funcaddr]Template arguments can be deduced from the type specified when taking the address of an overloadedfunction (13.4). The function template’s function type and the specified type are used as the types of P andA, and the deduction is done as described in 14.8.2.4.14.8.2.3 Deducing conversion function template arguments[temp.deduct.conv]1Template argument deduction is done by comparing the return type of the template conversion function(call it P) with the type that is required as the result of the conversion (call it A) as described in 14.8.2.4.2If A is not a reference type:— If P is an array type, the pointer type produced by the array-to-pointer standard conversion (4.2) is usedin place of P for type deduction; otherwise,— If P is a function type, the pointer type produced by the function-to-pointer standard conversion (4.3) isused in place of P for type deduction; otherwise,— If P is a cv-qualified type, the top level cv-qualifiers of P’s type are ignored for type deduction.If A is a cv-qualified type, the top level cv-qualifiers of A’s type are ignored for type deduction.

If A is areference type, the type referred to by A is used for type deduction.3In general, the deduction process attempts to find template argument values that will make the deduced Aidentical to A. However, there are two cases that allow a difference:— If the original A is a reference type, A can be more cv-qualified than the deduced A (i.e., the typereferred to by the reference)— The deduced A can be another pointer or pointer to member type that can be converted to A via a qualification conversion.These alternatives are considered only if type deduction would otherwise fail.

If they yield more than onepossible deduced A, the type deduction fails.14.8.2.4 Deducing template arguments from a type1[temp.deduct.type]Template arguments can be deduced in several different contexts, but in each case a type that is specified interms of template parameters (call it P) is compared with an actual type (call it A), and an attempt is madeto find template argument values (a type for a type parameter, a value for a non-type parameter, or a template for a template parameter) that will make P, after substitution of the deduced values (call it the deducedA), compatible with A.283ISO/IEC 14882:1998(E)14.8.2.4 Deducing template arguments from a type© ISO/IEC14 Templates2In some cases, the deduction is done using a single set of types P and A, in other cases, there will be a set ofcorresponding types P and A. Type deduction is done independently for each P/A pair, and the deducedtemplate argument values are then combined.

If type deduction cannot be done for any P/A pair, or if forany pair the deduction leads to more than one possible set of deduced values, or if different pairs yield different deduced values, or if any template argument remains neither deduced nor explicitly specified, template argument deduction fails.3A given type P can be composed from a number of other types, templates, and non-type values:— A function type includes the types of each of the function parameters and the return type.— A pointer to member type includes the type of the class object pointed to and the type of the memberpointed to.— A type that is a specialization of a class template (e.g., A<int>) includes the types, templates, andnon-type values referenced by the template argument list of the specialization.— An array type includes the array element type and the value of the array bound.In most cases, the types, templates, and non-type values that are used to compose P participate in templateargument deduction.

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

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

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

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