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

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

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

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

The instantiated default argumentis then used as the argument of f.13Each 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);// no default argument instantiationf(a, b);// default argument z = zdef(T()) instantiatedf(a);// ill-formed; ydef is not declared}— end example ]14[ Note: 14.6.4.1 defines the point of instantiation of a template specialization.

— end note ]15There 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:template<class T> class X {X<T>* p;// OKX<T*> a;// 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.2Explicit 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 instantiated fromthe member definition associated with its class template. An explicit instantiation of a function template ormember function of a class template shall not use the inline or constexpr specifiers.2The syntax for explicit instantiation is:§ 14.7.2370© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)explicit-instantiation:externopt template declarationThere are two forms of explicit instantiation: an explicit instantiation definition and an explicit instantiationdeclaration.

An explicit instantiation declaration begins with the extern keyword.3If the explicit instantiation is for a class or member class, the elaborated-type-specifier in the declaration shallinclude a simple-template-id. If the explicit instantiation is for a function or member function, the unqualifiedid in the declaration shall be either a template-id or, where all template arguments can be deduced, atemplate-name or operator-function-id.

[ Note: The declaration may declare a qualified-id, in which case theunqualified-id of the qualified-id must be a template-id. — end note ] If the explicit instantiation is for amember function, a member class or a static data member of a class template specialization, the name ofthe class template specialization in the qualified-id for the member name shall be a simple-template-id. Anexplicit instantiation shall appear in an enclosing namespace of its template. If the name declared in theexplicit instantiation is an unqualified name, the explicit instantiation shall appear in the namespace whereits template is declared or, if that namespace is inline (7.3.1), any namespace from its enclosing namespaceset.

[ Note: Regarding qualified names in declarators, see 8.3. — end note ] [ 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 ]4A declaration of a function template, a member function or static data member of a class template, or amember function template of a class or class template shall precede an explicit instantiation of that entity.A definition of a class template, a member class of a class template, or a member class template of a classor class template shall precede an explicit instantiation of that entity unless the explicit instantiation ispreceded by an explicit specialization of the entity with the same template arguments. If the declaration ofthe explicit instantiation names an implicitly-declared special member function (Clause 12), the program isill-formed.5For a given set of template arguments, if an explicit instantiation of a template appears after a declarationof an explicit specialization for that template, the explicit instantiation has no effect.

Otherwise, for anexplicit instantiation definition the definition of a function template, a member function template, or amember function or static data member of a class template shall be present in every translation unit inwhich it is explicitly instantiated.6An 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 namespacewhere the enclosing class template is defined.

An explicit instantiation for a member template is placed inthe namespace where the enclosing class or class template is defined. [ Example:namespace N {template<class T> class Y { void mf() { } };}template class Y<int>;// error: class template Y not visible§ 14.7.2© ISO/IEC 2011 – All rights reserved371ISO/IEC 14882:2011(E)// in the global namespaceusing N::Y;template class Y<int>;template class N::Y<char*>;template void N::Y<double>::mf();// error: explicit instantiation outside of the// namespace of the template// OK: explicit instantiation in namespace N// OK: explicit instantiation// in namespace N— end example ]7A trailing template-argument can be left unspecified in an explicit instantiation of a function templatespecialization or of a member function template specialization provided it can be deduced from the type ofa function 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 ]8An explicit instantiation that names a class template specialization is also an explicit instantiation of thesame kind (declaration or definition) of each of its members (not including members inherited from baseclasses) that has not been previously explicitly specialized in the translation unit containing the explicitinstantiation, except as described below. [ Note: In addition, it will typically be an explicit instantiation ofcertain implementation-dependent data about the class. — end note ]9An explicit instantiation definition that names a class template specialization explicitly instantiates theclass template specialization and is an explicit instantiation definition of only those members that have beendefined at the point of instantiation.10Except for inline functions and class template specializations, explicit instantiation declarations have theeffect of suppressing the implicit instantiation of the entity to which they refer.

[ Note: The intent is that aninline function that is the subject of an explicit instantiation declaration will still be implicitly instantiatedwhen odr-used (3.2) so that the body can be considered for inlining, but that no out-of-line copy of theinline function would be generated in the translation unit. — end note ]11If an entity is the subject of both an explicit instantiation declaration and an explicit instantiation definitionin the same translation unit, the definition shall follow the declaration. An entity that is the subject ofan explicit instantiation declaration and that is also used in a way that would otherwise cause an implicitinstantiation (14.7.1) in the translation unit shall be the subject of an explicit instantiation definition somewhere in the program; otherwise the program is ill-formed, no diagnostic required.

[ Note: This rule doesapply to inline functions even though an explicit instantiation declaration of such an entity has no othernormative effect. This is needed to ensure that if the address of an inline function is taken in a translationunit in which the implementation chose to suppress the out-of-line body, another translation unit will supplythe body. — end note ] An explicit instantiation declaration shall not name a specialization of a templatewith internal linkage.12The usual access checking rules do not apply to names used to specify explicit instantiations. [ Note: Inparticular, the template arguments and names used in the function declarator (including parameter types,return types and exception specifications) may be private types or objects which would normally not beaccessible and the template may be a member template or member function which would not normally beaccessible.

— end note ]§ 14.7.2372© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)13An explicit instantiation does not constitute a use of a default argument, so default argument instantiationis not done. [ Example:char* p = 0;template<class T> T g(T x = &p) { return x; }template int g<int>(int);// OK even though &p isn’t an int.— end example ]14.7.31Explicit specialization[temp.expl.spec]An 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 enumeration of a class template— member class template of a class or class template— member function template of a class or class templatecan 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-файл
Размер
14,26 Mb
Материал
Тип материала
Высшее учебное заведение

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

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