Главная » Просмотр файлов » B. Stroustrup - The C++ Programming Language

B. Stroustrup - The C++ Programming Language (794319), страница 24

Файл №794319 B. Stroustrup - The C++ Programming Language (B. Stroustrup - The C++ Programming Language) 24 страницаB. Stroustrup - The C++ Programming Language (794319) страница 242019-05-09СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

Inparticular, they are extensively used for parameterization of both types and algorithms in the standard library (§4.4.5, §4.5.5). For example, we can write a function that calculates the sum of theelement values of any container like this:80A Tour of C++: Abstraction MechanismsChapter 3template<typename Container, typename Value>Value sum(const Container& c, Value v){for (auto x : c)v+=x;return v;}The Value template argument and the function argument v are there to allow the caller to specify thetype and initial value of the accumulator (the variable in which to accumulate the sum):void user(Vector<int>& vi, std::list<double>& ld, std::vector<complex<double>>& vc){int x = sum(vi,0);// the sum of a vector of ints (add ints)double d = sum(vi,0.0);// the sum of a vector of ints (add doubles)double dd = sum(ld,0.0);// the sum of a list of doublesauto z = sum(vc,complex<double>{}); // the sum of a vector of complex<double>// the initial value is {0.0,0.0}}The point of adding ints in a double would be to gracefully handle a number larger than the largestint.

Note how the types of the template arguments for sum<T,V> are deduced from the functionarguments. Fortunately, we do not need to explicitly specify those types.This sum() is a simplified version of the standard-library accumulate() (§40.6).3.4.3 Function ObjectsOne particularly useful kind of template is the function object (sometimes called a functor), whichis used to define objects that can be called like functions.

For example:template<typename T>class Less_than {const T val;// value to compare againstpublic:Less_than(const T& v) :val(v) { }bool operator()(const T& x) const { return x<val; } // call operator};The function called operator() implements the ‘‘function call,’’ ‘‘call,’’ or ‘‘application’’ operator ().We can define named variables of type Less_than for some argument type:Less_than<int> lti {42};// lti(i) will compare i to 42 using < (i<42)Less_than<string> lts {"Backus"}; // lts(s) will compare s to "Backus" using < (s<"Backus")We can call such an object, just as we call a function:void fct(int n, const string & s){bool b1 = lti(n);// true if n<42bool b2 = lts(s);// true if s<"Backus"// ...}Section 3.4.3Function Objects81Such function objects are widely used as arguments to algorithms.

For example, we can count theoccurrences of values for which a predicate returns true:template<typename C, typename P>int count(const C& c, P pred){int cnt = 0;for (const auto& x : c)if (pred(x))++cnt;return cnt;}A predicate is something that we can invoke to return true or false. For example:void f(const Vector<int>& vec, const list<string>& lst, int x, const string& s){cout << "number of values less than " << x<< ": " << count(vec,Less_than<int>{x})<< '\n';cout << "number of values less than " << s<< ": " << count(lst,Less_than<string>{s})<< '\n';}Here, Less_than<int>{x} constructs an object for which the call operator compares to the int called x;Less_than<string>{s} constructs an object that compares to the string called s.

The beauty of thesefunction objects is that they carry the value to be compared against with them. We don’t have towrite a separate function for each value (and each type), and we don’t have to introduce nastyglobal variables to hold values. Also, for a simple function object like Less_than inlining is simple,so that a call of Less_than is far more efficient than an indirect function call. The ability to carrydata plus their efficiency make function objects particularly useful as arguments to algorithms.Function objects used to specify the meaning of key operations of a general algorithm (such asLess_than for count()) are often referred to as policy objects.We have to define Less_than separately from its use.

That could be seen as inconvenient. Consequently, there is a notation for implicitly generating function objects:void f(const Vector<int>& vec, const list<string>& lst, int x, const string& s){cout << "number of values less than " << x<< ": " << count(vec,[&](int a){ return a<x; })<< '\n';cout << "number of values less than " << s<< ": " << count(lst,[&](const string& a){ return a<s; })<< '\n';}The notation [&](int a){ return a<x; } is called a lambda expression (§11.4). It generates a functionobject exactly like Less_than<int>{x}. The [&] is a capture list specifying that local names used(such as x) will be passed by reference.

Had we wanted to ‘‘capture’’ only x, we could have said82A Tour of C++: Abstraction MechanismsChapter 3so: [&x]. Had we wanted to give the generated object a copy of x, we could have said so: [=x]. Capture nothing is [], capture all local names used by reference is [&], and capture all local names usedby value is [=].Using lambdas can be convenient and terse, but also obscure.

For nontrivial actions (say, morethan a simple expression), I prefer to name the operation so as to more clearly state its purpose andto make it available for use in several places in a program.In §3.2.4, we noticed the annoyance of having to write many functions to perform operations onelements of vectors of pointers and unique_ptrs, such as draw_all() and rotate_all(). Function objects(in particular, lambdas) can help by allowing us to separate the traversal of the container from thespecification of what is to be done with each element.First, we need a function that applies an operation to each object pointed to by the elements of acontainer of pointers:template<class C, class Oper>void for_all(C& c, Oper op)// assume that C is a container of pointers{for (auto& x : c)op(∗x);// pass op() a reference to each element pointed to}Now, we can write a version of user() from §3.2.4 without writing a set of _all functions:void user(){vector<unique_ptr<Shape>> v;while (cin)v.push_back(read_shape(cin));for_all(v,[](Shape& s){ s.draw(); });for_all(v,[](Shape& s){ s.rotate(45); });}// draw_all()// rotate_all(45)I pass a reference to Shape to a lambda so that the lambda doesn’t have to care exactly how theobjects are stored in the container.

In particular, those for_all() calls would still work if I changed vto a vector<Shape∗>.3.4.4 Variadic TemplatesA template can be defined to accept an arbitrary number of arguments of arbitrary types. Such atemplate is called a variadic template. For example:template<typename T, typename... Tail>void f(T head, Tail... tail){g(head); // do something to headf(tail...); // try again with tail}void f() { }// do nothingThe key to implementing a variadic template is to note that when you pass a list of arguments to it,Section 3.4.4Variadic Templates83you can separate the first argument from the rest. Here, we do something to the first argument (thehead) and then recursively call f() with the rest of the arguments (the tail).

The ellipsis, ..., is used toindicate ‘‘the rest’’ of a list. Eventually, of course, tail will become empty and we need a separatefunction to deal with that.We can call this f() like this:int main(){cout << "first: ";f(1,2.2,"hello");cout << "\nsecond: "f(0.2,'c',"yuck!",0,1,2);cout << "\n";}This would call f(1,2.2,"hello"), which will call f(2.2,"hello"), which will call f("hello"), which will callf(). What might the call g(head) do? Obviously, in a real program it will do whatever we wanteddone to each argument. For example, we could make it write its argument (here, head) to output:template<typename T>void g(T x){cout << x << " ";}Given that, the output will be:first: 1 2.2 hellosecond: 0.2 c yuck! 0 1 2It seems that f() is a simple variant of printf() printing arbitrary lists or values – implemented in threelines of code plus their surrounding declarations.The strength of variadic templates (sometimes just called variadics) is that they can accept anyarguments you care to give them.

The weakness is that the type checking of the interface is a possibly elaborate template program. For details, see §28.6. For examples, see §34.2.4.2 (N-tuples) andChapter 29 (N-dimensional matrices).3.4.5 AliasesSurprisingly often, it is useful to introduce a synonym for a type or a template (§6.5). For example,the standard header <cstddef> contains a definition of the alias size_t, maybe:using size_t = unsigned int;The actual type named size_t is implementation-dependent, so in another implementation size_tmay be an unsigned long.

Having the alias size_t allows the programmer to write portable code.It is very common for a parameterized type to provide an alias for types related to their templatearguments. For example:84A Tour of C++: Abstraction MechanismsChapter 3template<typename T>class Vector {public:using value_type = T;// ...};In fact, every standard-library container provides value_type as the name of its value type (§31.3.1).This allows us to write code that will work for every container that follows this convention. Forexample:template<typename C>using Element_type = typename C::value_type;template<typename Container>void algo(Container& c){Vector<Element_type<Container>> vec; // keep results here// ...}The aliasing mechanism can be used to define a new template by binding some or all template arguments.

For example:template<typename Key, typename Value>class Map {// ...};template<typename Value>using String_map = Map<string,Value>;String_map<int> m; // m is a Map<string,int>See §23.6.3.5 Advice[1][2][3][4][5][6][7]Express ideas directly in code; §3.2.Define classes to represent application concepts directly in code; §3.2.Use concrete classes to represent simple concepts and performance-critical components;§3.2.1.Avoid ‘‘naked’’ new and delete operations; §3.2.1.2.Use resource handles and RAII to manage resources; §3.2.1.2.Use abstract classes as interfaces when complete separation of interface and implementationis needed; §3.2.2.Use class hierarchies to represent concepts with inherent hierarchical structure; §3.2.4.Section 3.5[8][9][10][11][12][13][14][15]Advice85When designing a class hierarchy, distinguish between implementation inheritance and interface inheritance; §3.2.4.Control construction, copy, move, and destruction of objects; §3.3.Return containers by value (relying on move for efficiency); §3.3.2.Provide strong resource safety; that is, never leak anything that you think of as a resource;§3.3.3.Use containers, defined as resource handle templates, to hold collections of values of thesame type; §3.4.1.Use function templates to represent general algorithms; §3.4.2.Use function objects, including lambdas, to represent policies and actions; §3.4.3.Use type and template aliases to provide a uniform notation for types that may vary amongsimilar types or among implementations; §3.4.5.This page intentionally left blank4A Tour of C++: Containers and AlgorithmsWhy waste time learningwhen ignorance is instantaneous?– Hobbes••••••LibrariesStandard-Library Overview; The Standard-Library Headers and NamespaceStringsStream I/OOutput; Input; I/O of User-Defined TypesContainersvector; list; map; unordered_map; Container OverviewAlgorithmsUse of Iterators; Iterator Types; Stream Iterators; Predicates; Algorithm Overview; Container AlgorithmsAdvice4.1 LibrariesNo significant program is written in just a bare programming language.

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

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

Список файлов книги

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