Читаем 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>
Перейти на страницу:

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

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

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

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

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

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

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

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