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

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

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

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

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 simple-template-id. In the explicitspecialization declaration for a function template or a member function template, the name of the functionor member 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<> void g<int>(int) { }template<> int A<char>::x = 0;////////////template<class T = int> struct B {static int x;};template<> int B<>::x = 1;// specialize for T == inttemplate<> struct A<double> { };template<> struct A<> { };template<> void g(char) { }specialize for T == doublespecialize for T == intspecialize for U == charU is deduced from the parameter typespecialize for U == intspecialize for T == char142) Friend declarations do not introduce new names into any scope, either when the template is declared or when it isinstantiated.§ 14.7366© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)— 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).5For a given template and a given set of template-arguments,— an explicit instantiation definition shall appear at most once in a program,— an explicit specialization shall be defined at most once in a program (according to 3.2), and— both an explicit instantiation and a declaration of an explicit specialization shall not appear in aprogram unless the explicit instantiation follows a declaration of the explicit specialization.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:template<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*. — endexample ]14.7.11[temp.inst]Implicit instantiationUnless 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 a contextthat requires a completely-defined object type or when the completeness of the class type affects the semantics 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, scoped member enumerations, static data members and member templates; and itcauses the implicit instantiation of the definitions of unscoped member enumerations and member anonymous unions. However, for the purpose of determining whether an instantiated redeclaration of a memberis valid according to 9.2, a declaration that corresponds to a definition in the template is considered to be adefinition. [ Example:template<class T, class U>struct Outer {template<class X, class Y> structtemplate<class Y> struct Inner<T,template<class Y> struct Inner<T,template<class Y> struct Inner<U,};Outer<int, int> outer;Inner;Y>;Y> { };Y> { };// #1a// #1b; OK: valid redeclaration of #1a// #2// error at #2Outer<int, int>::Inner<int, Y> is redeclared at #1b.

(It is not defined but noted as being associatedwith a definition in Outer<T, U>.) #2 is also a redeclaration of #1a. It is noted as associated with adefinition, so it is an invalid redeclaration of the same partial specialization. — end example ]§ 14.7.1© ISO/IEC 2011 – All rights reserved367ISO/IEC 14882:2011(E)2Unless a member of a class template or a member template has been explicitly instantiated or explicitlyspecialized, the specialization of the member is implicitly instantiated when the specialization is referencedin a context that requires the member definition to exist; in particular, the initialization (and any associatedside-effects) of a static data member does not occur unless the static data member is itself used in a waythat requires the definition of the static data member to exist.3Unless 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.4[ Example:template<class T> struct Z {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 be implicitly instantiated.

— end example ]5A class template specialization is implicitly instantiated if the class type is used in a context that requiresa completely-defined object type or if the completeness of the class type might affect the semantics of theprogram. [ Note: In particular, if the semantics of an expression depend on the member or base class listsof a class template specialization, the class template specialization is implicitly generated. For instance,deleting a pointer to class type depends on whether or not the class declares a destructor, and conversionbetween pointer to class types depends on the inheritance relationship between the two classes involved.— end note ] [ Example:template<class T> class B { /∗ ...

∗/ };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 ]§ 14.7.1368© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)6If 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 ]7If 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 ]8The implicit instantiation of a class template does not cause any static data members of that class to beimplicitly instantiated.9If 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).10An 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 functionof a 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 thata class 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.11Implicitly 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 inthe namespace 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 {public:N::List<V> lt;§ 14.7.1© ISO/IEC 2011 – All rights reserved369ISO/IEC 14882:2011(E)V get(K);};void g(Map<const char*,int>& m) {int i = m.get("Nicholas");}a call of lt.get() from Map<const char*,int>::get() would place List<int>::get() in the namespaceN rather than in the global namespace.

— end example ]12If a function template f is called in a way that requires a default argument to be used, the dependent namesare looked up, the semantics constraints are checked, and the instantiation of any template used in the defaultargument is done as if the default argument had been an initializer used in a function template specializationwith the same scope, the same template parameters and the same access as that of the function template fused at that point. This analysis is called default argument instantiation.

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

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

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

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