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

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

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

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

If the primary member template is explicitly specializedfor a given (implicit) specialization of the enclosing class template, the partial specializations of the membertemplate are ignored for this specialization of the enclosing class template. If a partial specialization of themember template is explicitly specialized for a given (implicit) specialization of the enclosing class template,the primary member template and its other partial specializations are still considered for this specializationof the enclosing class template. [ Example:template<class T> struct A {template<class T2> struct B {};template<class T2> struct B<T2*> {};};// #1// #2template<> template<class T2> struct A<short>::B {};// #3A<char>::B<int*> abcip;A<short>::B<int*> absip;A<char>::B<int> abci;// uses #2// uses #3// uses #1— end example ]14.5.61Function templates[temp.fct]A function template defines an unbounded set of related functions.

[ Example: a family of sort functionsmight be declared like this:template<class T> class Array { };template<class T> void sort(Array<T>&);— end example ]2A function template can be overloaded with other function templates and with normal (non-template)functions. A normal function is not related to a function template (i.e., it is never considered to be a specialization), even if it has the same name and type as a potentially generated function template specialization.14114.5.6.11Function template overloading[temp.over.link]It is possible to overload function templates so that two different function template specializations have thesame type.

[ Example:// file1.ctemplate<class T>void f(T*);void g(int* p) {f(p); // calls f<int>(int*)}// file2.ctemplate<class T>void f(T);void h(int* p) {f(p); // calls f<int*>(int*)}— end example ]141) That is, declarations of non-template functions do not merely guide overload resolution of function template specializationswith the same name. If such a non-template function is odr-used (3.2) in a program, it must be defined; it will not be implicitlyinstantiated using the function template definition.§ 14.5.6.1© ISO/IEC 2011 – All rights reserved347ISO/IEC 14882:2011(E)2Such specializations are distinct functions and do not violate the one definition rule (3.2).3The signature of a function template is defined in 1.3.

The names of the template parameters are significantonly for establishing the relationship between the template parameters and the rest of the signature. [ Note:Two distinct function templates may have identical function return types and function parameter lists, evenif overload resolution alone cannot distinguish them.template<class T> void f();template<int I> void f();// OK: overloads the first template// distinguishable with an explicit template argument list— end note ]4When an expression that references a template parameter is used in the function parameter list or the returntype in the declaration of a function template, the expression that references the template parameter is partof the signature of the function template. This is necessary to permit a declaration of a function templatein one translation unit to be linked with another declaration of the function template in another translationunit and, conversely, to ensure that function templates that are intended to be distinct are not linked withone another.

[ Example:template <int I, int J> A<I+J> f(A<I>, A<J>);template <int K, int L> A<K+L> f(A<K>, A<L>);template <int I, int J> A<I-J> f(A<I>, A<J>);// #1// same as #1// different from #1— end example ] [ Note: Most expressions that use template parameters use non-type template parameters,but it is possible for an expression to reference a type parameter.

For example, a template type parametercan be used in the sizeof operator. — end note ]5Two expressions involving template parameters are considered equivalent if two function definitions containing the expressions would satisfy the one definition rule (3.2), except that the tokens used to name thetemplate parameters may differ as long as a token used to name a template parameter in one expression isreplaced by another token that names the same template parameter in the other expression.

[ Example:template <int I, int J> void f(A<I+J>);template <int K, int L> void f(A<K+L>);// #1// same as #1— end example ] Two expressions involving template parameters that are not equivalent are functionallyequivalent if, for any given set of template arguments, the evaluation of the expression results in the samevalue.6Two function templates are equivalent if they are declared in the same scope, have the same name, haveidentical template parameter lists, and have return types and parameter lists that are equivalent using therules described above to compare expressions involving template parameters. Two function templates arefunctionally equivalent if they are equivalent except that one or more expressions that involve templateparameters in the return types and parameter lists are functionally equivalent using the rules describedabove to compare expressions involving template parameters.

If a program contains declarations of functiontemplates that are functionally equivalent but not equivalent, the program is ill-formed; no diagnostic isrequired.7[ Note: This rule guarantees that equivalent declarations will be linked with one another, while not requiringimplementations to use heroic efforts to guarantee that functionally equivalent declarations will be treatedas distinct. For example, the last two declarations are functionally equivalent and would cause a programto be ill-formed:// Guaranteed to be the sametemplate <int I> void f(A<I>, A<I+10>);§ 14.5.6.1348© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)template <int I> void f(A<I>, A<I+10>);// Guaranteed to be differenttemplate <int I> void f(A<I>, A<I+10>);template <int I> void f(A<I>, A<I+11>);// Ill-formed, no diagnostic requiredtemplate <int I> void f(A<I>, A<I+10>);template <int I> void f(A<I>, A<I+1+2+3+4>);— end note ]14.5.6.21Partial ordering of function templates[temp.func.order]If a function template is overloaded, the use of a function template specialization might be ambiguousbecause template argument deduction (14.8.2) may associate the function template specialization with morethan one function template declaration.

Partial ordering of overloaded function template declarations isused in the following contexts to select the function template to which a function template specializationrefers:— during overload resolution for a call to a function template specialization (13.3.3);— when the address of a function template specialization is taken;— when a placement operator delete that is a function template specialization is selected to match aplacement operator new (3.7.4.2, 5.3.4);— when a friend function declaration (14.5.4), an explicit instantiation (14.7.2) or an explicit specialization (14.7.3) refers to a function template specialization.2Partial ordering selects which of two function templates is more specialized than the other by transformingeach template in turn (see next paragraph) and performing template argument deduction using the functiontype. The deduction process determines whether one of the templates is more specialized than the other.

Ifso, the more specialized template is the one chosen by the partial ordering process.3To produce the transformed template, for each type, non-type, or template template parameter (includingtemplate parameter packs (14.5.3) thereof) synthesize a unique type, value, or class template respectivelyand substitute it for each occurrence of that parameter in the function type of the template. If only oneof the function templates is a non-static member, that function template is considered to have a new firstparameter inserted in its function parameter list.

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

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

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

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