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

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

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

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

[Example:void g(double);void h();template<class T> class Z {public:void f() {g(1);h++;// calls g(double)// ill-formed: cannot increment function;// this could be diagnosed either here or// at the point of instantiation}};void g(int);// not in scope at the point of the template// definition, not considered for the call g(1)—end example]14.6.4 Dependent name resolution1[temp.dep.res]In resolving dependent names, names from the following sources are considered:— Declarations that are visible at the point of definition of the template.— Declarations from namespaces associated with the types of the function arguments both from the instantiation context (14.6.4.1) and from the definition context.14.6.4.1 Point of instantiation[temp.point]1For a function template specialization, a member function template specialization, or a specialization for amember function or static data member of a class template, if the specialization is implicitly instantiatedbecause it is referenced from within another template specialization and the context from which it is referenced depends on a template parameter, the point of instantiation of the specialization is the point of instantiation of the enclosing specialization.

Otherwise, the point of instantiation for such a specialization immediately follows the namespace scope declaration or definition that refers to the specialization.2If a function template or member function of a class template is called in a way which uses the definition ofa default argument of that function template or member function, the point of instantiation of the defaultargument is the point of instantiation of the function template or member function specialization.3For a class template specialization, a class member template specialization, or a specialization for a classmember of a class template, if the specialization is implicitly instantiated because it is referenced fromwithin another template specialization, if the context from which the specialization is referenced dependson a template parameter, and if the specialization is not instantiated previous to the instantiation of theenclosing template, the point of instantiation is immediately before the point of instantiation of the enclosing template.

Otherwise, the point of instantiation for such a specialization immediately precedes thenamespace scope declaration or definition that refers to the specialization.265ISO/IEC 14882:1998(E)© ISO/IEC14.6.4.1 Point of instantiation14 Templates4If a virtual function is implicitly instantiated, its point of instantiation is immediately following the point ofinstantiation of its enclosing class template specialization.5An explicit instantiation directive is an instantiation point for the specialization or specializations specifiedby the explicit instantiation directive.6The instantiation context of an expression that depends on the template arguments is the set of declarationswith external linkage declared prior to the point of instantiation of the template specialization in the sametranslation unit.7A specialization for a function template, a member function template, or of a member function or static datamember of a class template may have multiple points of instantiations within a translation unit.

A specialization for a class template has at most one point of instantiation within a translation unit. A specializationfor any template may have points of instantiation in multiple translation units. If two different points ofinstantiation give a template specialization different meanings according to the one definition rule (3.2), theprogram is ill-formed, no diagnostic required.14.6.4.2 Candidate functions1[temp.dep.candidate]For a function call that depends on a template parameter, if the function name is an unqualified-id but not atemplate-id, the candidate functions are found using the usual lookup rules (3.4.1, 3.4.2) except that:— For the part of the lookup using unqualified name lookup (3.4.1), only function declarations with external linkage from the template definition context are found.— For the part of the lookup using associated namespaces (3.4.2), only function declarations with externallinkage found in either the template definition context or the template instantiation context are found.If the call would be ill-formed or would find a better match had the lookup within the associated namespaces considered all the function declarations with external linkage introduced in those namespaces in alltranslation units, not just considering those declarations found in the template definition and templateinstantiation contexts, then the program has undefined behavior.14.6.5 Friend names declared within a class template[temp.inject]1Friend classes or functions can be declared within a class template.

When a template is instantiated, thenames of its friends are treated as if the specialization had been explicitly declared at its point of instantiation.2As with non-template classes, the names of namespace-scope friend functions of a class template specialization are not visible during an ordinary lookup unless explicitly declared at namespace scope (11.4).Such names may be found under the rules for associated classes (3.4.2).131) [Example:template<typename T> class number {number(int);//...friend number gcd(number& x, number& y) { /* ...

*/ }//...};__________________131) Friend declarations do not introduce new names into any scope, either when the template is declared or when it is instantiated.266© ISO/IEC14 TemplatesISO/IEC 14882:1998(E)14.6.5 Friend names declared within a class templatevoid g(){number<double> a(3), b(4);//...a = gcd(a,b);// finds gcd because number<double> is an// associated class, making gcd visible// in its namespace (global scope)b = gcd(3,4);// ill-formed; gcd is not visible}—end example]14.7 Template instantiation and specialization[temp.spec]1The act of instantiating a function, a class, a member of a class template or a member template is referred toas template instantiation.2A function instantiated from a function template is called an instantiated function.

A class instantiated froma class template is called an instantiated class. A member function, a member class, or a static data memberof a class template instantiated from the member definition of the class template is called, respectively, aninstantiated member function, member class or static data member. A member function instantiated from amember function template is called an instantiated member function. A member class instantiated from amember class template is called an instantiated member class.3An explicit specialization may be declared for a function template, a class template, a member of a classtemplate or a member template.

An explicit specialization declaration is introduced by template<>. Inan explicit specialization declaration for a class template, a member of a class template or a class membertemplate, the name of the class that is explicitly specialized shall be a template-id. In the explicit specialization declaration for a function template or a member function template, the name of the function ormember function explicitly specialized may be a template-id.

[Example:template<class T = int> struct A {static int x;};template<class U> void g(U) { }template<> struct A<double> { };template<> struct A<> { };template<> void g(char) { }template<> void g<int>(int) { }template<> int A<char>::x = 0;// specialize for T == double// specialize for T == int// specialize for U == char// U is deduced from the parameter type// specialize for U == int// specialize for T == chartemplate<class T = int> struct B {static int x;};template<> int B<>::x = 1;// specialize for T == int—end example]4An instantiated template specialization can be either implicitly instantiated (14.7.1) for a given argumentlist or be explicitly instantiated (14.7.2). A specialization is a class, function, or class member that is eitherinstantiated or explicitly specialized (14.7.3).5No program shall explicitly instantiate any template more than once, both explicitly instantiate and explicitly specialize a template, or specialize a template more than once for a given set of template-arguments.An implementation is not required to diagnose a violation of this rule.6Each class template specialization instantiated from a template has its own copy of any static members.[Example:267ISO/IEC 14882:1998(E)© ISO/IEC14.7 Template instantiation and specialization14 Templatestemplate<class T> class X {static T s;// ...};template<class T> T X<T>::s = 0;X<int> aa;X<char*> bb;X<int> has a static member s of type int and X<char*> has a static member s of type char*.

]14.7.1 Implicit instantiation[temp.inst]1Unless a class template specialization has been explicitly instantiated (14.7.2) or explicitly specialized(14.7.3), the class template specialization is implicitly instantiated when the specialization is referenced in acontext that requires a completely-defined object type or when the completeness of the class type affects thesemantics of the program. The implicit instantiation of a class template specialization causes the implicitinstantiation of the declarations, but not of the definitions or default arguments, of the class member functions, member classes, static data members and member templates; and it causes the implicit instantiationof the definitions of member anonymous unions.

Unless a member of a class template or a member template has been explicitly instantiated or explicitly specialized, the specialization of the member is implicitlyinstantiated when the specialization is referenced in a context that requires the member definition to exist;in particular, the initialization (and any associated side-effects) of a static data member does not occurunless the static data member is itself used in a way that requires the definition of the static data member toexist.2Unless a function template specialization has been explicitly instantiated or explicitly specialized, the function template specialization is implicitly instantiated when the specialization is referenced in a context thatrequires a function definition to exist.

Unless a call is to a function template explicit specialization or to amember function of an explicitly specialized class template, a default argument for a function template or amember function of a class template is implicitly instantiated when the function is called in a context thatrequires the value of the default argument.3[Example:template<class T> class Z {public:void f();void g();};void h(){Z<int> a;Z<char>* p;Z<double>* q;a.f();p->g();// instantiation of class Z<int> required// instantiation of class Z<char> not// required// instantiation of class Z<double>// not required// instantiation of Z<int>::f() required// instantiation of class Z<char> required, and// instantiation of Z<char>::g() required}Nothing in this example requires class Z<double>, Z<int>::g(), or Z<char>::f() to beimplicitly instantiated.

]4A class template specialization is implicitly instantiated if the class type is used in a context that requires acompletely-defined object type or if the completeness of the class type affects the semantics of the program;in particular, if an expression whose type is a class template specialization is involved in overload resolution, pointer conversion, pointer to member conversion, the class template specialization is implicitly268© ISO/IECISO/IEC 14882:1998(E)14 Templates14.7.1 Implicit instantiationinstantiated (3.2); in addition, a class template specialization is implicitly instantiated if the operand of adelete expression is of class type or is of pointer to class type and the class type is a template specialization.[Example:template<class T> class B { /* ...

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

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

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

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