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

To let the compiler know that you need a particular form of swap function, you just use a function called Swap() in your program. The compiler checks the argument types you use and then generates the corresponding function. Listing 8.11 shows how this works. The program layout follows the usual pattern for ordinary functions, with a template function prototype near the top of the file and the template function definition following main(). The example follows the more usual practice of using T instead of AnyType as the type parameter.

Listing 8.11. funtemp.cpp

// funtemp.cpp -- using a function template

#include

// function template prototype

template   // or class T

void Swap(T &a, T &b);

int main()

{

    using namespace std;

    int i = 10;

    int j = 20;

    cout << "i, j = " << i << ", " << j << ".\n";

    cout << "Using compiler-generated int swapper:\n";

    Swap(i,j);  // generates void Swap(int &, int &)

    cout << "Now i, j = " << i << ", " << j << ".\n";

    double x = 24.5;

    double y = 81.7;

    cout << "x, y = " << x << ", " << y << ".\n";

    cout << "Using compiler-generated double swapper:\n";

    Swap(x,y);  // generates void Swap(double &, double &)

    cout << "Now x, y = " << x << ", " << y << ".\n";

    // cin.get();

    return 0;

}

// function template definition

template   // or class T

void Swap(T &a, T &b)

{

    T temp;   // temp a variable of type T

    temp = a;

    a = b;

    b = temp;

}

The first Swap() function in Listing 8.11 has two int arguments, so the compiler generates an int version of the function. That is, it replaces each use of T with int, producing a definition that looks like this:

void Swap(int &a, int &b)

{

    int temp;

    temp = a;

    a = b;

    b = temp;

}

You don’t see this code, but the compiler generates and then uses it in the program. The second Swap() function has two double arguments, so the compiler generates a double version. That is, it replaces T with double, generating this code:

void Swap(double &a, double &b)

{

    double temp;

    temp = a;

    a = b;

    b = temp;

}

Here’s the output of the program in Listing 8.11, which shows that the process has worked:

i, j = 10, 20.

Using compiler-generated int swapper:

Now i, j = 20, 10.

x, y = 24.5, 81.7.

Using compiler-generated double swapper:

Now x, y = 81.7, 24.5.

Note that function templates don’t make executable programs any shorter. In Listing 8.11, you still wind up with two separate function definitions, just as you would if you defined each function manually. And the final code doesn’t contain any templates; it just contains the actual functions generated for the program. The benefits of templates are that they make generating multiple function definitions simpler and more reliable.

More typically, templates are placed in a header file that is then included in the file using them. Chapter 9 discusses header files.

Overloaded Templates

You use templates when you need functions that apply the same algorithm to a variety of types, as in Listing 8.11. It might be, however, that not all types would use the same algorithm. To handle this possibility, you can overload template definitions, just as you overload regular function definitions. As with ordinary overloading, overloaded templates need distinct function signatures. For example, Listing 8.12 adds a new swapping template—one for swapping elements of two arrays. The original template has the signature (T &, T &), whereas the new template has the signature (T [], T [], int). Note that the final parameter in this case happens to be a specific type (int) rather than a generic type. Not all template arguments have to be template parameter types.

When, in twotemps.cpp, the compiler encounters the first use of Swap(), it notices that it has two int arguments and matches Swap() to the original template. The second use, however, has two int arrays and an int value as arguments, and this matches the new template.

Listing 8.12. twotemps.cpp

// twotemps.cpp -- using overloaded template functions

#include

template      // original template

void Swap(T &a, T &b);

template      // new template

void Swap(T *a, T *b, int n);

void Show(int a[]);

const int Lim = 8;

int main()

{

    using namespace std;

    int i = 10, j = 20;

    cout << "i, j = " << i << ", " << j << ".\n";

    cout << "Using compiler-generated int swapper:\n";

    Swap(i,j);              // matches original template

    cout << "Now i, j = " << i << ", " << j << ".\n";

    int d1[Lim] = {0,7,0,4,1,7,7,6};

    int d2[Lim] = {0,7,2,0,1,9,6,9};

    cout << "Original arrays:\n";

    Show(d1);

    Show(d2);

    Swap(d1,d2,Lim);        // matches new template

    cout << "Swapped arrays:\n";

    Show(d1);

    Show(d2);

    // cin.get();

    return 0;

}

template

void Swap(T &a, T &b)

{

    T temp;

    temp = a;

    a = b;

    b = temp;

}

template

void Swap(T a[], T b[], int n)

{

    T temp;

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

    {

        temp = a[i];

        a[i] = b[i];

        b[i] = temp;

    }

}

void Show(int a[])

{

    using namespace std;

    cout << a[0] << a[1] << "/";

    cout << a[2] << a[3] << "/";

    for (int i = 4; i < Lim; i++)

        cout << a[i];

    cout << endl;

}

Here is the output of the program in Listing 8.12:

i, j = 10, 20.

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

Все книги серии 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.

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

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