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

Another important idea to take away from this chapter is that a template implies an interface. That is, even though the template keyword says "I’ll take any type," the code in a template definition actually requires that certain operators and member functions be supported—that’s the interface. So in reality, a template definition is saying, "I’ll take any type that supports this interface." Things would be much nicer if the compiler could simply say, "Hey, this type that you’re trying to instantiate the template with doesn’t support that interface—can’t do it." Using templates, therefore, constitutes a sort of "latent type checking" that is more flexible than the pure object-oriented practice of requiring all types to derive from certain base classes.

In Chapters 6 and 7 we explore in depth the most famous application of templates, the subset of the standard C++ library commonly known as the Standard Template Library (STL). Chapters 9 and 10 also use template techniques not found in this chapter.

<p>Exercises</p>

             1.             Write a unary function template that takes a single type template parameter. Create a full specialization for the type int. Also create a non-template overload for this function that takes a single int parameter. Have your main program invoke three function variations.

             2.             Write a class template that uses a vector to implement a stack data structure.

        38.             Modify your solution to the previous exercise so that the type of the container used to implement the stack is a template template parameter.

        39.             In the following code, the class NonComparable does not have an operator=( ). Why would the presence of the class HardLogic cause a compile error, but SoftLogic would not?

class Noncomparable {};

struct HardLogic {

  Noncomparable nc1, nc2;

  void compare() {

     return nc1 == nc2; // Compiler error

  }

};

template

struct SoftLogic {

  Noncomparable nc1, nc2;

  void noOp() {}

  void compare() {

    nc1 == nc2;

  }

};

int main() {

  SoftLogic l;

  l.noOp(); }

        40.             Write a function template that takes a single type parameter (T) and accepts four function arguments: an array of T, a start index, a stop index (inclusive), and an optional initial value. The function returns the sum of all the array elements in the specified range. Use the default constructor of T for the default initial value.

         41.             Repeat the previous exercise but use explicit instantiation to manually create specializations for int and double, following the technique explained in this chapter.

        42.             Why does the following code not compile? (Hint: what do class member functions have access to?)

class Buddy {};

template

class My {

  int i;

public:

  void play(My& s) {

    s.i = 3;

  }

};

int main() {

  My h;

  My me, bud;

  h.play(bud);

  me.play(bud);

}

        43.             Why does the following code not compile?

template

double pythag(T a, T b, T c) {

  return (-b + sqrt(double(b*b - 4*a*c))) / 2*a;

}

int main() {

  pythag(1, 2, 3);

  pythag(1.0, 2.0, 3.0);

  pythag(1, 2.0, 3.0);

  pythag(1, 2.0, 3.0);

}

        44.             Write templates that take non-type parameters of the following variety: an int, a pointer to an int, a pointer to a static class member of type int, and a pointer to a static member function.

        45.             Write a class template that takes two type parameters. Define a partial specialization for the first parameter, and another partial specialization that specifies the second parameter. In each specialization, introduce members that are not in the primary template.

        46.             Define a class template named Bob that takes a single type parameter. Make Bob a friend of all instances of a template class named Friendly, and a friend of a class template named Picky only when the type parameter of Bob and Picky are identical. Give Bob member functions that demonstrate its friendship.

<p>6: Generic algorithms</p>

Algorithms are at the core of computing. To be able to write an algorithm once and for all to work with any type of sequence makes your programs both simpler and safer. The ability to customize algorithms at runtime has revolutionized software development.

The subset of the standard C++ library known as the Standard Template Library (STL) was originally designed around generic algorithms—code that processes sequences of any type of values in a type-safe manner. The goal was to use predefined algorithms for almost every task, instead of hand-coding loops every time you need to process a collection of data. This power comes with a bit of a learning curve, however. By the time you get to the end of this chapter, you should be able to decide for yourself whether you find the algorithms addictive or too confusing to remember. If you’re like most people, you’ll resist them at first but then tend to use them more and more.

<p>A first look</p>
Перейти на страницу:

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

3ds Max 2008
3ds Max 2008

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

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

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