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

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

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

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

For a friend function declaration that is not a template declaration:— if the name of the friend is a qualified or unqualified template-id, the friend declaration refers to a specialization of a function template, otherwise— if the name of the friend is a qualified-id and a matching nontemplate function is found in the specifiedclass or namespace, the friend declaration refers to that function, otherwise,— if the name of the friend is a qualified-id and a matching specialization of a template function is foundin the specified class or namespace, the friend declaration refers to that function specialization, otherwise,— the name shall be an unqualified-id that declares (or redeclares) an ordinary (nontemplate) function.[Example:template<class T> class task;template<class T> task<T>* preempt(task<T>*);template<class T> class task {// ...friend void next_time();friend void process(task<T>*);friend task<T>* preempt<T>(task<T>*);template<class C> friend int func(C);friend class task<int>;template<class P> friend class frd;// ...};Here, each specialization of the task class template has the function next_time as a friend; becauseprocess does not have explicit template-arguments, each specialization of the task class template hasan appropriately typed function process as a friend, and this friend is not a function template specialization; because the friend preempt has an explicit template-argument <T>, each specialization of the taskclass template has the appropriate specialization of the function template preempt as a friend; and eachspecialization of the task class template has all specializations of the function template func as friends.Similarly, each specialization of the task class template has the class template specialization task<int>as a friend, and has all specializations of the class template frd as friends.

—end example]2A friend function declaration that is not a template declaration and in which the name of the friend is anunqualified template-id shall refer to a specialization of a function template declared in the nearest enclosing namespace scope. [Example:248© ISO/IECISO/IEC 14882:1998(E)14 Templatesnamespace N {template <class T> void f(T);void g(int);namespace M {template <class T> void h(T);template <class T> void i(T);struct A {friend void f<>(int);friend void h<>(int);friend void g(int);template <class T> voidfriend void i<>(int);};}}14.5.3 Friends// ill-formed – N::f// OK – M::h// OK – new decl of M::gi(T);// ill-formed – A::i—end example]3A friend template may be declared within a class or class template.

A friend function template may bedefined within a class or class template, but a friend class template may not be defined in a class or classtemplate. In these cases, all specializations of the friend class or friend function template are friends of theclass or class template granting friendship. [Example:class A {template<class T> friend class B;// OKtemplate<class T> friend void f(T){ /* ... */ }};// OK—end example]4A template friend declaration specifies that all specializations of that template, whether they are implicitlyinstantiated (14.7.1), partially specialized (14.5.4) or explicitly specialized (14.7.3), are friends of the classcontaining the template friend declaration.

[Example:class X {template<class T> friend struct A;class Y { };};template<class T> struct A { X::Y ab; };template<class T> struct A<T*> { X::Y ab; };// OK// OK—end example]5When a function is defined in a friend function declaration in a class template, the function is defined ateach instantiation of the class template. The function is defined even if it is never used. The same restrictions on multiple declarations and definitions which apply to non-template function declarations and definitions also apply to these implicit definitions.

[Note: if the function definition is ill-formed for a given specialization of the enclosing class template, the program is ill-formed even if the function is never used. ]6A member of a class template may be declared to be a friend of a non-template class. In this case, the corresponding member of every specialization of the class template is a friend of the class granting friendship.[Example:249ISO/IEC 14882:1998(E)© ISO/IEC14.5.3 Friends14 Templatestemplate<class T> struct A {struct B { };void f();};class C {template<class T> friend struct A<T>::B;template<class T> friend void A<T>::f();};—end example]7[Note: a friend declaration may first declare a member of an enclosing namespace scope (14.6.5).

]8A friend template shall not be declared in a local class.9Friend declarations shall not declare partial specializations. [Example:template<class T> class A { };class X {template<class T> friend class A<T*>;};// error—end example]10When a friend declaration refers to a specialization of a function template, the function parameter declarations shall not include default arguments, nor shall the inline specifier be used in such a declaration.14.5.4 Class template partial specializations[temp.class.spec]1A primary class template declaration is one in which the class template name is an identifier.

A templatedeclaration in which the class template name is a template-id, is a partial specialization of the class template named in the template-id. A partial specialization of a class template provides an alternative definition of the template that is used instead of the primary definition when the arguments in a specializationmatch those given in the partial specialization (14.5.4.1). The primary template shall be declared beforeany specializations of that template. If a template is partially specialized then that partial specializationshall be declared before the first use of that partial specialization that would cause an implicit instantiationto take place, in every translation unit in which such a use occurs; no diagnostic is required.2When a partial specialization is used within the instantiation of an exported template, and the unspecializedtemplate name is non-dependent in the exported template, a declaration of the partial specialization must bedeclared before the definition of the exported template, in the translation unit containing that definition.

Asimilar restriction applies to explicit specialization; see 14.7.3Each class template partial specialization is a distinct template and definitions shall be provided for themembers of a template partial specialization (14.5.4.3).4[Example:template<classtemplate<classtemplate<classtemplate<classtemplate<classT1, class T2, int I>T, int I>T1, class T2, int I>T>T1, class T2, int I>classclassclassclassclassAA<T, T*, I>A<T1*, T2, I>A<int, T*, 5>A<T1, T2*, I>{{{{{};};};};};// #1// #2// #3// #4// #5The first declaration declares the primary (unspecialized) class template. The second and subsequent declarations declare partial specializations of the primary template. ]5The template parameters are specified in the angle bracket enclosed list that immediately follows the keyword template. For partial specializations, the template argument list is explicitly written immediatelyfollowing the class template name.

For primary templates, this list is implicitly described by the templateparameter list. Specifically, the order of the template arguments is the sequence in which they appear in thetemplate parameter list. [Example: the template argument list for the primary template in the example250© ISO/IECISO/IEC 14882:1998(E)14 Templates14.5.4 Class template partial specializationsabove is <T1, T2, I>. ] [Note: the template argument list shall not be specified in the primary templatedeclaration. For example,template<class T1, class T2, int I> class A<T1, T2, I>{ };// error—end note]6A class template partial specialization may be declared or redeclared in any namespace scope in which itsdefinition may be defined (14.5.1 and 14.5.2).

[Example:template<class T> struct A {class C {template<class T2> struct B { };};};// partial specialization of A<T>::C::B<T2>template<class T> template<class T2>struct A<T>::C::B<T2*> { };A<short>::C::B<int*> absip;// uses partial specialization—end example]7Partial specialization declarations themselves are not found by name lookup. Rather, when the primarytemplate name is used, any previously declared partial specializations of the primary template are also considered. One consequence is that a using-declaration which refers to a class template does not restrict theset of partial specializations which may be found through the using-declaration.

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

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

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

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