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

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

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

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

T, class... U> void f() { }template<class... T, class U> void g() { }— end example ]12A template-parameter shall not be given default arguments by two different declarations in the same scope.[ Example:template<class T = int> class X;template<class T = int> class X { /∗... ∗/ }; // error— end example ]13When parsing a default template-argument for a non-type template-parameter, the first non-nested > is takenas the end of the template-parameter-list rather than a greater-than operator. [ Example:template<int i = 3 > 4 >class X { /∗ ...

∗/ };// syntax errortemplate<int i = (3 > 4) >class Y { /∗ ... ∗/ };// OK— end example ]14A template-parameter of a template template-parameter is permitted to have a default template-argument.When such default arguments are specified, they apply to the template template-parameter in the scope ofthe template template-parameter. [ Example:§ 14.1324© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)template <class T = float> struct B {};template <template <class TT = float> class T> struct A {inline void f();inline void g();};template <template <class TT> class T> void A<T>::f() {T<> t;// error - TT has no default template argument}template <template <class TT = char> class T> void A<T>::g() {T<> t;// OK - T<char>}— end example ]15If a template-parameter is a type-parameter with an ellipsis prior to its optional identifier or is a parameterdeclaration that declares a parameter pack (8.3.5), then the template-parameter is a template parameterpack (14.5.3).

A template parameter pack that is a parameter-declaration whose type contains one or moreunexpanded parameter packs is a pack expansion. Similarly, a template parameter pack that is a typeparameter with a template-parameter-list containing one or more unexpanded parameter packs is a packexpansion. A template parameter pack that is a pack expansion shall not expand a parameter pack declaredin the same template-parameter-list. [ Example:template <class... Types> class Tuple;template <class T, int... Dims> struct multi_array;template<class...

T> struct value_holder {template<T... Values> apply { };////////Types is a template type parameter packbut not a pack expansionDims is a non-type template parameter packbut not a pack expansion// Values is a non-type template parameter pack// and a pack expansion};template<class... T, T... Values> struct static_array;// error: Values expands template type parameter// pack T within the same template parameter list— end example ]14.21Names of template specializations[temp.names]A template specialization (14.7) can be referred to by a template-id:simple-template-id:template-name < template-argument-listopt >template-id:simple-template-idoperator-function-id < template-argument-listopt >literal-operator-id < template-argument-listopt >template-name:identifiertemplate-argument-list:template-argument ...opttemplate-argument-list , template-argument ...opttemplate-argument:constant-expressiontype-idid-expression§ 14.2© ISO/IEC 2011 – All rights reserved325ISO/IEC 14882:2011(E)[ Note: The name lookup rules (3.4) are used to associate the use of a name with a template declaration;that is, to identify a name as a template-name.

— end note ]2For a template-name to be explicitly qualified by the template arguments, the name must be known to referto a template.3After name lookup (3.4) finds that a name is a template-name or that an operator-function-id or a literaloperator-id refers to a set of overloaded functions any member of which is a function template if this isfollowed by a <, the < is always taken as the delimiter of a template-argument-list and never as the less-thanoperator. When parsing a template-argument-list, the first non-nested >138 is taken as the ending delimiterrather than a greater-than operator.

Similarly, the first non-nested >> is treated as two consecutive butdistinct > tokens, the first of which is taken as the end of the template-argument-list and completes thetemplate-id. [ Note: The second > token produced by this replacement rule may terminate an enclosingtemplate-id construct or it may be part of a different construct (e.g. a cast). — end note ] [ Example:template<int i> class X { /* ...*/ };X< 1>2 > x1;X<(1>2)> x2;// syntax error// OKtemplate<class T> class Y { /* ...Y<X<1>> x3;Y<X<6>>1>> x4;Y<X<(6>>1)>> x5;*///////};OK, same as Y<X<1> > x3;syntax errorOK— end example ]4When the name of a member template specialization appears after .

or -> in a postfix-expression or after anested-name-specifier in a qualified-id, and the object expression of the postfix-expression is type-dependentor the nested-name-specifier in the qualified-id refers to a dependent type, but the name is not a member ofthe current instantiation (14.6.2.1), the member template name must be prefixed by the keyword template.Otherwise the name is assumed to name a non-template. [ Example:struct X {template<std::size_t> X* alloc();template<std::size_t> static X* adjust();};template<class T> void f(T* p) {T* p1 = p->alloc<200>();// ill-formed: <T* p2 = p->template alloc<200>(); // OK: < startsT::adjust<100>();// ill-formed: <T::template adjust<100>();// OK: < starts}means less thantemplate argument listmeans less thantemplate argument list— end example ]5A name prefixed by the keyword template shall be a template-id or the name shall refer to a class template.[ Note: The keyword template may not be applied to non-template members of class templates.

— endnote ] [ Note: As is the case with the typename prefix, the template prefix is allowed in cases where it isnot strictly necessary; i.e., when the nested-name-specifier or the expression on the left of the -> or . is notdependent on a template-parameter, or the use does not appear in the scope of a template. — end note ][ Example:138) A > that encloses the type-id of a dynamic_cast, static_cast, reinterpret_cast or const_cast, or which encloses thetemplate-arguments of a subsequent template-id, is considered nested for the purpose of this description.§ 14.2326© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)template <class T> struct A {void f(int);template <class U> void f(U);};template <class T> void f(T t) {A<T> a;a.template f<>(t);a.template f(t);}// OK: calls template// error: not a template-idtemplate <class T> struct B {template <class T2> struct C { };};// OK: T::template C names a class template:template <class T, template <class X> class TT = T::template C> struct D { };D<b<int> > db;— end example ]6A simple-template-id that names a class template specialization is a class-name (Clause 9).7A template-id that names an alias template specialization is a type-name.14.31Template arguments[temp.arg]There are three forms of template-argument, corresponding to the three forms of template-parameter: type,non-type and template.

The type and form of each template-argument specified in a template-id shallmatch the type and form specified for the corresponding parameter declared by the template in its templateparameter-list. When the parameter declared by the template is a template parameter pack (14.5.3), it willcorrespond to zero or more template-arguments.

[ Example:template<class T> class Array {T* v;int sz;public:explicit Array(int);T& operator[](int);T& elem(int i) { return v[i]; }};Array<int> v1(20);typedef std::complex<double> dcomplex;// std::complex is a standard// library templateArray<dcomplex> v2(30);Array<dcomplex> v3(40);void bar() {v1[3] = 7;v2[3] = v3.elem(4) = dcomplex(7,8);}— end example ]§ 14.3© ISO/IEC 2011 – All rights reserved327ISO/IEC 14882:2011(E)2In a template-argument, an ambiguity between a type-id and an expression is resolved to a type-id, regardlessof the form of the corresponding template-parameter.139 [ Example:template<class T> void f();template<int I> void f();void g() {f<int()>();}// int() is a type-id: call the first f()— end example ]3The name of a template-argument shall be accessible at the point where it is used as a template-argument.[ Note: If the name of the template-argument is accessible at the point where it is used as a templateargument, there is no further access restriction in the resulting instantiation where the correspondingtemplate-parameter name is used.

— end note ] [ Example:template<class T> class X {static T t;};class Y {private:struct S { /∗ ... ∗/ };X<S> x;// OK: S is accessible// X<Y::S> has a static member of type Y::S// OK: even though Y::S is private};X<Y::S> y;// error: S not accessible— end example ] For a template-argument that is a class type or a class template, the template definitionhas no special access rights to the members of the template-argument.

[ Example:template <template <class TT> class T> class A {typename T<int>::S s;};template <class U> class B {private:struct S { /∗ ... ∗/ };};A<B> b;// ill-formed: A has no access to B::S— end example ]4When template argument packs or default template-arguments are used, a template-argument list can beempty. In that case the empty <> brackets shall still be used as the template-argument-list. [ Example:template<class T = char> class String;String<>* p;// OK: String<char>String* q;// syntax errortemplate<class ... Elements> class Tuple;139) There is no such ambiguity in a default template-argument because the form of the template-parameter determines theallowable forms of the template-argument.§ 14.3328© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)Tuple<>* t;Tuple* u;// OK: Elements is empty// syntax error— end example ]5An explicit destructor call (12.4) for an object that has a type that is a class template specialization mayexplicitly specify the template-arguments.

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

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

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

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