Читаем Thinking In C++. Volume 2: Practical Programming полностью

Since these names are expected of all standard function objects as well as of any function objects you create that you want to use with the function object adapters, the header provides two templates that define these types for you: unary_function and binary_function. You simply derive from these classes while filling in the argument types as template parameters. Suppose, for example, that we want to make the function object gt_n, defined earlier in this chapter, adaptable. All we need to do is the following:.

class gt_n : public unary_function {

  int value;

public:

  gt_n(int val) : value(val) {}

  bool operator()(int n) {

    return n > value;

  }

};.

All unary_function does is to provide the appropriate type definitions, which it infers from its template parameters as you can see in its definition:.

template

struct unary_function {

  typedef Arg argument_type;

  typedef Result result_type;

};

These types become accessible through gt_n because it derives publicly from unary_function. The binary_function template behaves in a similar manner.

<p>More function object examples</p>

The following FunctionObjects.cpp example provides simple tests for most of the built-in basic function object templates. This way, you can see how to use each template, along with their resulting behavior. This example uses one of the following generators for convenience:.

//: C06:Generators.h

// Different ways to fill sequences

#ifndef GENERATORS_H

#define GENERATORS_H

#include

#include

#include

#include

// Microsoft namespace work-around

#ifndef _MSC_VER

using std::rand;

using std::srand;

using std::time;

#endif

// A generator that can skip over numbers:

class SkipGen {

  int i;

  int skp;

public:

  SkipGen(int start = 0, int skip = 1)

    : i(start), skp(skip) {}

  int operator()() {

    int r = i;

    i += skp;

    return r;

  }

};

// Generate unique random numbers from 0 to mod:

class URandGen {

  std::set used;

  int limit;

public:

  URandGen(int lim) : limit(lim) {

    srand(time(0));

  }

  int operator()() {

    while(true) {

      int i = int(rand()) % limit;

      if(used.find(i) == used.end()) {

        used.insert(i);

        return i;

      }

    }

  }

};

// Produces random characters:

class CharGen {

  static const char* source;

  static const int len;

public:

  CharGen() { srand(time(0)); }

  char operator()() {

    return source[rand() % len];

  }

};

// Statics created here for convenience, but

// will cause problems if multiply included:

const char* CharGen::source = "ABCDEFGHIJK"

  "LMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

const int CharGen::len = strlen(source);

#endif // GENERATORS_H ///:~

We’ll be using these generating functions in various examples throughout this chapter. The SkipGen function object returns the next number of an arithmetic sequence whose common difference is held in its skp data member. A URandGen object generates a unique random number in a specified range. (It uses a set container, which we’ll discuss in the next chapter.) A CharGen object returns a random alphabetic character. Here is the sample program we promised, which uses URandGen.

//: C06:FunctionObjects.cpp

//{-bor}

// Illustrates selected predefined function object

// templates from the standard C++ library

#include

#include

#include

#include

#include

#include "Generators.h"

using namespace std;

template

void print(Iter b, Iter e, char* msg = "") {

  if(msg != 0 && *msg != 0)

    cout << msg << ":" << endl;

  typedef typename Iter::value_type T;

  copy(b, e, ostream_iterator(cout, " "));

  cout << endl;

}

template

void testUnary(Contain& source, Contain& dest,

  UnaryFunc f) {

  transform(source.begin(), source.end(),

    dest.begin(), f);

}

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

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

3ds Max 2008
3ds Max 2008

Одни уверены, что нет лучшего способа обучения 3ds Мах, чем прочитать хорошую книгу. Другие склоняются к тому, что эффективнее учиться у преподавателя, который показывает, что и как нужно делать. Данное издание объединяет оба подхода. Его цель – сделать освоение 3ds Мах 2008 максимально быстрым и результативным. Часто после изучения книги у читателя возникают вопросы, почему не получился тот или иной пример. Видеокурс – это гарантия, что такие вопросы не возникнут: ведь автор не только рассказывает, но и показывает, как нужно работать в 3ds Мах.В отличие от большинства интерактивных курсов, где работа в 3ds Мах иллюстрируется на кубиках-шариках, данный видеокурс полностью практический. Все приемы работы с инструментами 3ds Мах 2008 показаны на конкретных примерах, благодаря чему после просмотра курса читатель сможет самостоятельно выполнять даже сложные проекты.

Владимир Антонович Верстак , Владимир Верстак

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