Читаем C++ Primer Plus полностью

This makes the identifier ShowReview have the type void (*)(const Review &), so that is the type assigned to the template argument Function. With a different function call, the Function argument could represent a class type that has an overloaded () operator. Ultimately, the for_each() code will have an expression using f(). In the ShowReview() example, f is a pointer to a function, and f() invokes the function. If the final for_each() argument is an object, then f() becomes the object that invokes its overloaded () operator.

Functor Concepts

Just as the STL defines concepts for containers and iterators, it defines functor concepts:

• A generator is a functor that can be called with no arguments.

• A unary function is a functor that can be called with one argument.

• A binary function is a functor that can be called with two arguments.

For example, the functor supplied to for_each() should be a unary function because it is applied to one container element at a time.

Of course, these concepts come with refinements:

• A unary function that returns a bool value is a predicate.

• A binary function that returns a bool value is a binary predicate.

Several STL functions require predicate or binary predicate arguments. For example, Listing 16.9 uses a version of sort() that takes a binary predicate as its third argument:

bool WorseThan(const Review & r1, const Review & r2);

...

sort(books.begin(), books.end(), WorseThan);

The list template has a remove_if() member that takes a predicate as an argument. It applies the predicate to each member in the indicated range, removing those elements for which the predicate returns true. For example, the following code would remove all elements greater than 100 from the list three:

bool tooBig(int n){ return n > 100; }

list scores;

...

scores.remove_if(tooBig);

Incidentally, this last example shows where a class functor might be useful. Suppose you want to remove every value greater than 200 from a second list. It would be nice if you could pass the cut-off value to tooBig() as a second argument so you could use the function with different values, but a predicate can have but one argument. If, however, you design a TooBig class, you can use class members instead of function arguments to convey additional information:

template

class TooBig

{

private:

    T cutoff;

public:

    TooBig(const T & t) : cutoff(t) {}

    bool operator()(const T & v) { return v > cutoff; }

};

Here one value (v) is passed as a function argument, and the second argument (cutoff) is set by the class constructor. Given this definition, you can initialize different TooBig objects to different cut-off values to be used in calls to remove_if(). Listing 16.15 illustrates the technique.

Listing 16.15. functor.cpp

// functor.cpp -- using a functor

#include

#include

#include

#include

template  // functor class defines operator()()

class TooBig

{

private:

    T cutoff;

public:

    TooBig(const T & t) : cutoff(t) {}

    bool operator()(const T & v) { return v > cutoff; }

};

void outint(int n) {std::cout << n << " ";}

int main()

{

    using std::list;

    using std::cout;

    using std::endl;

    TooBig f100(100); // limit = 100

    int vals[10] = {50, 100, 90, 180, 60, 210, 415, 88, 188, 201};

    list yadayada(vals, vals + 10); // range constructor

    list etcetera(vals, vals + 10);

 // C++11 can use the following instead

//  list yadayada = {50, 100, 90, 180, 60, 210, 415, 88, 188, 201};

//  list etcetera {50, 100, 90, 180, 60, 210, 415, 88, 188, 201};

    cout << "Original lists:\n";

    for_each(yadayada.begin(), yadayada.end(), outint);

    cout << endl;

    for_each(etcetera.begin(), etcetera.end(), outint);

    cout << endl;

    yadayada.remove_if(f100);               // use a named function object

    etcetera.remove_if(TooBig(200));   // construct a function object

    cout <<"Trimmed lists:\n";

    for_each(yadayada.begin(), yadayada.end(), outint);

    cout << endl;

    for_each(etcetera.begin(), etcetera.end(), outint);

    cout << endl;

    return 0;

}

One functor (f100) is a declared object, and the second (TooBig(200)) is an anonymous object created by a constructor call. Here’s the output of the program in Listing 16.15:

Original lists:

50 100 90 180 60 210 415 88 188 201

50 100 90 180 60 210 415 88 188 201

Trimmed lists:

50 100 90 60 88

50 100 90 180 60 88 188

Suppose that you already have a template function with two arguments:

template

bool tooBig(const T & val, const T & lim)

{

    return val > lim;

}

You can use a class to convert it to a one-argument function object:

template

class TooBig2

{

private:

    T cutoff;

public:

    TooBig2(const T & t) : cutoff(t) {}

Перейти на страницу:

Все книги серии Developer's Library

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных

Похожие книги

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных