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

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

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

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

Types> struct Tuple { };Tuple<> t0;Tuple<int> t1;Tuple<int, float> t2;Tuple<0> error;////////TypesTypesTypeserror:contains no argumentscontains one argument: intcontains two arguments: int and float0 is not a type— end example ]2A function parameter pack is a function parameter that accepts zero or more function arguments. [ Example:template<class ... Types> void f(Types ... args);f();f(1);f(2, 1.0);// OK: args contains no arguments// OK: args contains one argument: int// OK: args contains two arguments: int and double— end example ]3A parameter pack is either a template parameter pack or a function parameter pack.4A pack expansion consists of a pattern and an ellipsis, the instantiation of which produces zero or moreinstantiations of the pattern in a list (described below).

The form of the pattern depends on the context inwhich the expansion occurs. Pack expansions can occur in the following contexts:— In a function parameter pack (8.3.5); the pattern is the parameter-declaration without the ellipsis.— In a template parameter pack that is a pack expansion (14.1):— if the template parameter pack is a parameter-declaration; the pattern is the parameter-declarationwithout the ellipsis;— if the template parameter pack is a type-parameter with a template-parameter-list; the pattern isthe corresponding type-parameter without the ellipsis.— In an initializer-list (8.5); the pattern is an initializer-clause.— In a base-specifier-list (Clause 10); the pattern is a base-specifier.— In a mem-initializer-list (12.6.2); the pattern is a mem-initializer.— In a template-argument-list (14.3); the pattern is a template-argument.— In a dynamic-exception-specification (15.4); the pattern is a type-id.— In an attribute-list (7.6.1); the pattern is an attribute.— In an alignment-specifier (7.6.2); the pattern is the alignment-specifier without the ellipsis.— In a capture-list (5.1.2); the pattern is a capture.— In a sizeof...

expression (5.3.3); the pattern is an identifier.[ Example:§ 14.5.3© ISO/IEC 2011 – All rights reserved339ISO/IEC 14882:2011(E)template<class ... Types> void f(Types ... rest);template<class ... Types> void g(Types ... rest) {f(&rest ...);// “&rest ...” is a pack expansion; “&rest” is its pattern}— end example ]5A parameter pack whose name appears within the pattern of a pack expansion is expanded by that packexpansion. An appearance of the name of a parameter pack is only expanded by the innermost enclosingpack expansion.

The pattern of a pack expansion shall name one or more parameter packs that are notexpanded by a nested pack expansion; such parameter packs are called unexpanded parameter packs in thepattern. All of the parameter packs expanded by a pack expansion shall have the same number of argumentsspecified. An appearance of a name of a parameter pack that is not expanded is ill-formed. [ Example:template<typename...> struct Tuple {};template<typename T1, typename T2> struct Pair {};template<class ...

Args1> struct zip {template<class ... Args2> struct with {typedef Tuple<Pair<Args1, Args2> ... > type;};};typedef zip<short, int>::with<unsigned short, unsigned>::type T1;// T1 is Tuple<Pair<short, unsigned short>, Pair<int, unsigned>>typedef zip<short>::with<unsigned short, unsigned>::type T2;// error: different number of arguments specified for Args1 and Args2template<class ... Args>void g(Args ... args) {f(const_cast<const Args*>(&args)...);f(5 ...);f(args);f(h(args ...) + args ...);////////////OK: Args is expanded by the function parameter pack argsOK: “Args” and “args” are expandederror: pattern does not contain any parameter packserror: parameter pack “args” is not expandedOK: first “args” expanded within h, second“args” expanded within f}— end example ]6The instantiation of a pack expansion that is not a sizeof...

expression produces a list E1 , E2 , ..., EN , whereN is the number of elements in the pack expansion parameters. Each Ei is generated by instantiating thepattern and replacing each pack expansion parameter with its ith element. All of the Ei become elementsin the enclosing list. [ Note: The variety of list varies with the context: expression-list, base-specifier-list,template-argument-list, etc. — end note ] When N is zero, the instantiation of the expansion produces anempty list. Such an instantiation does not alter the syntactic interpretation of the enclosing construct, evenin cases where omitting the list entirely would otherwise be ill-formed or would result in an ambiguity inthe grammar.

[ Example:template<class... T> struct X : T... { };template<class... T> void f(T... values) {X<T...> x(values...);}template void f<>();// OK: X<> has no base classes// x is a variable of type X<> that is value-initialized§ 14.5.3340© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)— end example ]7The instantiation of a sizeof... expression (5.3.3) produces an integral constant containing the numberof elements in the parameter pack it expands.14.5.41Friends[temp.friend]A friend of a class or class template can be a function template or class template, a specialization of afunction template or class template, or an ordinary (non-template) function or class.

For a friend functiondeclaration that is not a template declaration:— if the name of the friend is a qualified or unqualified template-id, the friend declaration refers to aspecialization of a function template, otherwise— if the name of the friend is a qualified-id and a matching non-template function is found in the specifiedclass or namespace, the friend declaration refers to that function, otherwise,— if the name of the friend is a qualified-id and a matching function template is found in the specified class or namespace, the friend declaration refers to the deduced specialization of that functiontemplate (14.8.2.6), otherwise,— the name shall be an unqualified-id that declares (or redeclares) an ordinary (non-template) function.[ Example:template<class T> class task;template<class T> task<T>* preempt(task<T>*);template<class T> class task {friend void next_time();friend void process(task<T>*);friend task<T>* preempt<T>(task<T>*);template<class C> friend int func(C);friend class task<int>;template<class P> friend class frd;};Here, each specialization of the task class template has the function next_time as a friend; because processdoes not have explicit template-arguments, each specialization of the task class template has an appropriatelytyped function process as a friend, and this friend is not a function template specialization; because thefriend preempt has an explicit template-argument <T>, each specialization of the task class template hasthe appropriate specialization of the function template preempt as a friend; and each specialization ofthe task class template has all specializations of the function template func as friends.

Similarly, eachspecialization of the task class template has the class template specialization task<int> as a friend, andhas all specializations of the class template frd as friends. — end example ]2A friend template may be declared within a class or class template. A friend function template may bedefined within a class or class template, but a friend class template may not be defined in a class or classtemplate. In these cases, all specializations of the friend class or friend function template are friends of theclass or class template granting friendship. [ Example:class A {template<class T> friend class B;template<class T> friend void f(T){ /* ...};*/ }// OK// OK§ 14.5.4© ISO/IEC 2011 – All rights reserved341ISO/IEC 14882:2011(E)— end example ]3A template friend declaration specifies that all specializations of that template, whether they are implicitlyinstantiated (14.7.1), partially specialized (14.5.5) or explicitly specialized (14.7.3), are friends of the classcontaining the template friend declaration.

[ Example:class X {template<class T> friend struct A;class Y { };};// OK// OKtemplate<class T> struct A { X::Y ab; };template<class T> struct A<T*> { X::Y ab; };— end example ]4When a function is defined in a friend function declaration in a class template, the function is instantiatedwhen the function is odr-used. The same restrictions on multiple declarations and definitions that apply tonon-template function declarations and definitions also apply to these implicit definitions.5A member of a class template may be declared to be a friend of a non-template class. In this case, thecorresponding member of every specialization of the class template is a friend of the class granting friendship.For explicit specializations the corresponding member is the member (if any) that has the same name, kind(type, function, class template, or function template), template parameters, and signature as the memberof the class template instantiation that would otherwise have been generated.

[ Example:template<class T> struct A {struct B { };void f();struct D {void g();};};template<> struct A<int> {struct B { };int f();struct D {void g();};};class C {template<class T> friend struct A<T>::B;////template<class T> friend void A<T>::f();////template<class T> friend void A<T>::D::g(); ////};grants friendship to A<int>::B even thoughit is not a specialization of A<T>::Bdoes not grant friendship to A<int>::f()because its return type does not matchdoes not grant friendship to A<int>::D::g()because A<int>::D is not a specialization of A<T>::D— end example ]6[ Note: A friend declaration may first declare a member of an enclosing namespace scope (14.6.5).

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

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

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

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