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

template

         class A1, class A2>

void apply(Seq& sq, R(T::*f)(A1, A2),

    A1 a1, A2 a2) {

  typename Seq::iterator it = sq.begin();

  while(it != sq.end()) {

    ((*it)->*f)(a1, a2);

    it++;

  }

}

// Etc., to handle maximum likely arguments ///:~

The apply( ) function template takes a reference to the container class and a pointer-to-member for a member function of the objects contained in the class. It uses an iterator to move through the Stack and apply the function to every object.

Notice that there are no STL header files (or any header files, for that matter) included in applySequence.h, so it is actually not limited to use with an STL container. However, it does make assumptions (primarily, the name and behavior of the iterator) that apply to STL sequences.

You can see there is more than one version of apply( ), further illustrating overloading of function templates. Although these templates allow any type of return value (which is ignored, but the type information is required to match the pointer-to-member), each version takes a different number of arguments, and because it’s a template, those arguments can be of any type. The only limitation here is that there’s no "super template" to create templates for you; you must decide how many arguments will ever be required.

To test the various overloaded versions of apply( ), the class Gromit[57] is created containing functions with different numbers of arguments:.

//: C05:Gromit.h

// The techno-dog. Has member functions

// with various numbers of arguments.

#include

class Gromit {

  int arf;

public:

  Gromit(int arf = 1) : arf(arf + 1) {}

  void speak(int) {

    for(int i = 0; i < arf; i++)

      std::cout << "arf! ";

    std::cout << std::endl;

  }

  char eat(float) {

    std::cout << "chomp!" << std::endl;

    return 'z';

  }

  int sleep(char, double) {

    std::cout << "zzz..." << std::endl;

    return 0;

  }

  void sit() {

    std::cout << " Sitting...)" << std::endl;

  }

}; ///:~

Now you can use the apply( ) template functions to apply the Gromit member functions to a vector, like this:.

//: C05:ApplyGromit.cpp

// Test ApplySequence.h

#include

#include

#include

#include "ApplySequence.h"

#include "Gromit.h"

using namespace std;

int main() {

  vector dogs;

  for(size_t i = 0; i < 5; i++)

    dogs.push_back(new Gromit(i));

  apply(dogs, &Gromit::speak, 1);

  apply(dogs, &Gromit::eat, 2.0f);

  apply(dogs, &Gromit::sleep, 'z', 3.0);

  apply(dogs, &Gromit::sit);

  for (size_t i = 0; i < dogs.size(); ++i)

    delete dogs[i];

} ///:~

Although the definition of apply( ) is somewhat complex and not something you’d ever expect a novice to understand, its use is remarkably clean and simple, and a novice could easily use it knowing only what it is intended to accomplish, not how. This is the type of division you should strive for in all your program components: The tough details are all isolated on the designer’s side of the wall. Users are concerned only with accomplishing their goals and don’t see, know about, or depend on details of the underlying implementation. We’ll explore even more flexible ways to apply functions to sequences in the next chapter.

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

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

3ds Max 2008
3ds Max 2008

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

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

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