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

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

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

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

*/ };template<class T> class D : public B<T> { /* ... */ };void f(void*);void f(B<int>*);void g(D<int>* p, D<char>* pp, D<double> ppp){f(p);// instantiation of D<int> required: call f(B<int>*)B<char>* q = pp;// instantiation of D<char> required:// convert D<char>* to B<char>*delete ppp;// instantiation of D<double> required}—end example]5If the overload resolution process can determine the correct function to call without instantiating a classtemplate definition, it is unspecified whether that instantiation actually takes place.

[Example:template <class T> struct S {operator int();};void f(int);void f(S<int>&);void f(S<float>);void g(S<int>& sr) {f(sr);// instantiation of S<int> allowed but not required// instantiation of S<float> allowed but not required};—end example]6If an implicit instantiation of a class template specialization is required and the template is declared but notdefined, the program is ill-formed. [Example:template<class T> class X;X<char> ch;// error: definition of X required—end example]7The implicit instantiation of a class template does not cause any static data members of that class to beimplicitly instantiated.8If a function template or a member function template specialization is used in a way that involves overloadresolution, a declaration of the specialization is implicitly instantiated (14.8.3).9An implementation shall not implicitly instantiate a function template, a member template, a non-virtualmember function, a member class or a static data member of a class template that does not require instantiation.

It is unspecified whether or not an implementation implicitly instantiates a virtual member function ofa class template if the virtual member function would not otherwise be instantiated. The use of a templatespecialization in a default argument shall not cause the template to be implicitly instantiated except that aclass template may be instantiated where its complete type is needed to determine the correctness of thedefault argument.

The use of a default argument in a function call causes specializations in the defaultargument to be implicitly instantiated.269ISO/IEC 14882:1998(E)© ISO/IEC14.7.1 Implicit instantiation1014 TemplatesImplicitly instantiated class and function template specializations are placed in the namespace where thetemplate is defined. Implicitly instantiated specializations for members of a class template are placed in thenamespace where the enclosing class template is defined. Implicitly instantiated member templates areplaced in the namespace where the enclosing class or class template is defined.

[Example:namespace N {template<class T> class List {public:T* get();// ...};}template<class K, class V> class Map {N::List<V> lt;V get(K);// ...};void g(Map<char*,int>& m){int i = m.get("Nicholas");// ...}a call of lt.get() from Map<char*,int>::get() would place List<int>::get() in thenamespace N rather than in the global namespace.

]11If a function template f is called in a way that requires a default argument expression to be used, the dependent names are looked up, the semantics constraints are checked, and the instantiation of any template usedin the default argument expression is done as if the default argument expression had been an expressionused in a function template specialization with the same scope, the same template parameters and the sameaccess as that of the function template f used at that point. This analysis is called default argumentinstantiation. The instantiated default argument is then used as the argument of f.12Each default argument is instantiated independently.

[Example:template<class T> void f(T x, T y = ydef(T()), T z = zdef(T()));classA { };A zdef(A);void g(A a, A b, A c) {f(a, b, c);f(a, b);f(a);}// no default argument instantiation// default argument z = zdef(T()) instantiated// ill-formed; ydef is not declared—end example]13[Note: 14.6.4.1 defines the point of instantiation of a template specialization. ]14There is an implementation-defined quantity that specifies the limit on the total depth of recursive instantiations, which could involve more than one template. The result of an infinite recursion in instantiation isundefined.

[Example:270© ISO/IECISO/IEC 14882:1998(E)14 Templatestemplate<class T> class X {X<T>* p;X<T*> a;14.7.1 Implicit instantiation// OK// implicit generation of X<T> requires// the implicit instantiation of X<T*> which requires// the implicit instantiation of X<T**> which ...};—end example]14.7.2 Explicit instantiation[temp.explicit]1A class, a function or member template specialization can be explicitly instantiated from its template. Amember function, member class or static data member of a class template can be explicitly instantiatedfrom the member definition associated with its class template.2The syntax for explicit instantiation is:explicit-instantiation:template declarationIf the explicit instantiation is for a class, a function or a member template specialization, the unqualified-idin the declaration shall be either a template-id or, where all template arguments can be deduced, atemplate-name.

[Note: the declaration may declare a qualified-id, in which case the unqualified-id of thequalified-id must be a template-id. ] If the explicit instantiation is for a member function, a member classor a static data member of a class template specialization, the name of the class template specialization inthe qualified-id for the member declarator shall be a template-id.

[Example:template<class T> class Array { void mf(); };template class Array<char>;template void Array<int>::mf();template<class T> void sort(Array<T>& v) { /* ... */ }template void sort(Array<char>&);// argument is deduced herenamespace N {template<class T> void f(T&) { }}template void N::f<int>(int&);—end example]3A declaration of a function template shall be in scope at the point of the explicit instantiation of the functiontemplate. A definition of the class or class template containing a member function template shall be inscope at the point of the explicit instantiation of the member function template. A definition of a class template or class member template shall be in scope at the point of the explicit instantiation of the class template or class member template.

A definition of a class template shall be in scope at the point of an explicitinstantiation of a member function or a static data member of the class template. A definition of a memberclass of a class template shall be in scope at the point of an explicit instantiation of the member class.

If thedeclaration of the explicit instantiation names an implicitly-declared special member function (clause 12),the program is ill-formed.4The definition of a non-exported function template, a non-exported member function template, or a nonexported member function or static data member of a class template shall be present in every translationunit in which it is explicitly instantiated.5An explicit instantiation of a class or function template specialization is placed in the namespace in whichthe template is defined. An explicit instantiation for a member of a class template is placed in the namespace where the enclosing class template is defined.

An explicit instantiation for a member template isplaced in the namespace where the enclosing class or class template is defined. [Example:271ISO/IEC 14882:1998(E)© ISO/IEC14.7.2 Explicit instantiation14 Templatesnamespace N {template<class T> class Y { void mf() { } };}template class Y<int>;using N::Y;template class Y<int>;// error: class template Y not visible// in the global namespace// OK: explicit instantiation in namespace Ntemplate class N::Y<char*>;template void N::Y<double>::mf();// OK: explicit instantiation in namespace N// OK: explicit instantiation// in namespace N—end example]6A trailing template-argument can be left unspecified in an explicit instantiation of a function template specialization or of a member function template specialization provided it can be deduced from the type of afunction parameter (14.8.2).

[Example:template<class T> class Array { /* ... */ };template<class T> void sort(Array<T>& v);// instantiate sort(Array<int>&) – template-argument deducedtemplate void sort<>(Array<int>&);—end example]7The explicit instantiation of a class template specialization implies the instantiation of all of its membersnot previously explicitly specialized in the translation unit containing the explicit instantiation.8The usual access checking rules do not apply to names used to specify explicit instantiations.

[Note: In particular, the template arguments and names used in the function declarator (including parameter types, returntypes and exception specifications) may be private types or objects which would normally not be accessibleand the template may be a member template or member function which would not normally be accessible.]9An explicit instantiation does not constitute a use of a default argument, so default argument instantiation isnot done. [Example:char* p = 0;template<class T> T g(T = &p);template int g<int>(int);// OK even though &p isn’t an int.—end example]14.7.3 Explicit specialization1An explicit specialization of any of the following:— function template— class template— member function of a class template— static data member of a class template— member class of a class template— member class template of a class template— member function template of a class template272[temp.expl.spec]© ISO/IECISO/IEC 14882:1998(E)14 Templates14.7.3 Explicit specializationcan be declared by a declaration introduced by template<>; that is:explicit-specialization:template < > declaration[Example:template<class T> class stream;template<> class stream<char> { /* ...

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

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

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

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