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

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

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

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

[Example:template<class E, int size> class buffer { /* ... */ };buffer<char,2*512> x;buffer<char,1024> y;declares x and y to be of the same type, andtemplate<class T, void(*err_fct)()> class list { /* ... */ };list<int,&error_handler1> x1;list<int,&error_handler2> x2;list<int,&error_handler2> x3;list<char,&error_handler2> x4;declares x2 and x3 to be of the same type.

Their type differs from the types of x1 and x4. ]14.5 Template declarations1[temp.decls]A template-id, that is, the template-name followed by a template-argument-list shall not be specified in thedeclaration of a primary template declaration. [Example:template<class T1, class T2, int I> class A<T1, T2, I> { };template<class T1, int I> void sort<T1, I>(T1 data[I]);// error// error—end example] [Note: however, this syntax is allowed in class template partial specializations (14.5.4). ]2For purposes of name lookup and instantiation, default arguments of function templates and default arguments of member functions of class templates are considered definitions; each default argument is a separate definition which is unrelated to the function template definition or to any other default arguments.14.5.1 Class templates1[temp.class]A class template defines the layout and operations for an unbounded set of related types.

[Example: a single class template List might provide a common definition for list of int, list of float, and list ofpointers to Shapes. ]244© ISO/IECISO/IEC 14882:1998(E)14 Templates214.5.1 Class templates[Example: An array class template might be declared like this:template<class T> class Array {T* v;int sz;public:explicit Array(int);T& operator[](int);T& elem(int i) { return v[i]; }// ...};The prefix template <class T> specifies that a template is being declared and that a type-name T willbe used in the declaration.

In other words, Array is a parameterized type with T as its parameter. ]3When a member function, a member class, a static data member or a member template of a class template isdefined outside of the class template definition, the member definition is defined as a template definition inwhich the template-parameters are those of the class template. The names of the template parameters usedin the definition of the member may be different from the template parameter names used in the class template definition. The template argument list following the class template name in the member definitionshall name the parameters in the same order as the one used in the template parameter list of the member.[Example:template<class T1, class T2> struct A {void f1();void f2();};template<class T2, class T1> void A<T2,T1>::f1() { }template<class T2, class T1> void A<T1,T2>::f2() { }// OK// error—end example]4In a redeclaration, partial specialiation, explicit specialization or explicit instantiation of a class template,the class-key shall agree in kind with the original class template declaration (7.1.5.3).14.5.1.1 Member functions of class templates1[temp.mem.func]A member function template may be defined outside of the class template definition in which it is declared.[Example:template<class T> class Array {T* v;int sz;public:explicit Array(int);T& operator[](int);T& elem(int i) { return v[i]; }// ...};declares three function templates.

The subscript function might be defined like this:template<class T> T& Array<T>::operator[](int i){if (i<0 || sz<=i) error("Array: range error");return v[i];}—end example]2The template-arguments for a member function of a class template are determined by the templatearguments of the type of the object for which the member function is called. [Example: the templateargument for Array<T>::operator[]() will be determined by the Array to which the subscripting245ISO/IEC 14882:1998(E)© ISO/IEC14.5.1.1 Member functions of class templates14 Templatesoperation is applied.Array<int> v1(20);Array<dcomplex> v2(30);v1[3] = 7;v2[3] = dcomplex(7,8);// Array<int>::operator[]()// Array<dcomplex>::operator[]()—end example]14.5.1.2 Member classes of class templates1[temp.mem.class]A class member of a class template may be defined outside the class template definition in which it isdeclared.

[Note: the class member must be defined before its first use that requires an instantiation (14.7.1).For example,template<class T> struct A {class B;};A<int>::B* b1;// OK: requires A to be defined but not A::Btemplate<class T> class A<T>::B { };A<int>::B b2;// OK: requires A::B to be defined—end note]14.5.1.3 Static data members of class templates1[temp.static]A definition for a static data member may be provided in a namespace scope enclosing the definition of thestatic member’s class template.

[Example:template<class T> class X {static T s;};template<class T> T X<T>::s = 0;—end example]14.5.2 Member templates1[temp.mem]A template can be declared within a class or class template; such a template is called a member template. Amember template can be defined within or outside its class definition or class template definition.

A member template of a class template that is defined outside of its class template definition shall be specified withthe template-parameters of the class template followed by the template-parameters of the member template. [Example:template<class T> class string {public:template<class T2> int compare(const T2&);template<class T2> string(const string<T2>& s) { /* ...

*/ }// ...};template<class T> template<class T2> int string<T>::compare(const T2& s){// ...}—end example]2A local class shall not have member templates. Access control rules (clause 11) apply to member templatenames. A destructor shall not be a member template. A normal (non-template) member function with agiven name and type and a member function template of the same name, which could be used to generate aspecialization of the same type, can both be declared in a class.

When both exist, a use of that name andtype refers to the non-template member unless an explicit template argument list is supplied. [Example:246© ISO/IECISO/IEC 14882:1998(E)14 Templates14.5.2 Member templatestemplate <class T> struct A {void f(int);template <class T2> void f(T2);};template <> void A<int>::f(int) { }template <> template <> void A<int>::f<>(int) { }int main(){A<char> ac;ac.f(1);ac.f(’c’);ac.f<>(1);}// non-template member// template member// non-template// template// template—end example]3A member function template shall not be virtual. [Example:template <class T> struct AA {template <class C> virtual void g(C);virtual void f();};// error// OK—end example]4A specialization of a member function template does not override a virtual function from a base class.[Example:class B {virtual void f(int);};class D : public B {template <class T> void f(T);void f(int i) { f<>(i); }// does not override B::f(int)// overriding function that calls// the template instantiation};—end example]5A specialization of a template conversion function is referenced in the same way as a non-template conversion function that converts to the same type.

[Example:struct A {template <class T> operator T*();};template <class T> A::operator T*(){ return 0; }template <> A::operator char*(){ return 0; }// specializationtemplate A::operator void*();// explicit instantiationint main(){Aint*a;ip;ip = a.operator int*();// explicit call to template operator// A::operator int*()}—end example] [Note: because the explicit template argument list follows the function template name, andbecause conversion member function templates and constructor member function templates are called without using a function name, there is no way to provide an explicit template argument list for these function247ISO/IEC 14882:1998(E)14.5.2 Member templates© ISO/IEC14 Templatestemplates. ]6A specialization of a template conversion function is not found by name lookup.

Instead, any template conversion functions visible in the context of the use are considered. For each such operator, if argumentdeduction succeeds (14.8.2.3), the resulting specialization is used as if found by name lookup.7A using-declaration in a derived class cannot refer to a specialization of a template conversion function in abase class.8Overload resolution (13.3.3.2) and partial ordering (14.5.5.2) are used to select the best conversion functionamong multiple template conversion functions and/or non-template conversion functions.14.5.3 Friends1[temp.friend]A friend of a class or class template can be a function template or class template, a specialization of a function template or class template, or an ordinary (nontemplate) function or class.

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

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

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

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