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

Listing 8.13 illustrates how explicit specialization works.

Listing 8.13. twoswap.cpp

// twoswap.cpp -- specialization overrides a template

#include

template

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

struct job

{

    char name[40];

    double salary;

    int floor;

};

// explicit specialization

template <> void Swap(job &j1, job &j2);

void Show(job &j);

int main()

{

    using namespace std;

    cout.precision(2);

    cout.setf(ios::fixed, ios::floatfield);

    int i = 10, 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";

    job sue = {"Susan Yaffee", 73000.60, 7};

    job sidney = {"Sidney Taffee", 78060.72, 9};

    cout << "Before job swapping:\n";

    Show(sue);

    Show(sidney);

    Swap(sue, sidney); // uses void Swap(job &, job &)

    cout << "After job swapping:\n";

    Show(sue);

    Show(sidney);

    // cin.get();

    return 0;

}

template

void Swap(T &a, T &b)    // general version

{

    T temp;

    temp = a;

    a = b;

    b = temp;

}

// swaps just the salary and floor fields of a job structure

template <> void Swap(job &j1, job &j2)  // specialization

{

    double t1;

    int t2;

    t1 = j1.salary;

    j1.salary = j2.salary;

    j2.salary = t1;

    t2 = j1.floor;

    j1.floor = j2.floor;

    j2.floor = t2;

}

void Show(job &j)

{

    using namespace std;

    cout << j.name << ": $" << j.salary

         << " on floor " << j.floor << endl;

}

Here’s the output of the program in Listing 8.13:

i, j = 10, 20.

Using compiler-generated int swapper:

Now i, j = 20, 10.

Before job swapping:

Susan Yaffee: $73000.60 on floor 7

Sidney Taffee: $78060.72 on floor 9

After job swapping:

Susan Yaffee: $78060.72 on floor 9

Sidney Taffee: $73000.60 on floor 7

Instantiations and Specializations

To extend your understanding of templates, let’s investigate the terms instantiation and specialization. Keep in mind that including a function template in your code does not in itself generate a function definition. It’s merely a plan for generating a function definition. When the compiler uses the template to generate a function definition for a particular type, the result is termed an instantiation of the template. For example, in Listing 8.13, the function call Swap(i,j) causes the compiler to generate an instantiation of Swap(), using int as the type. The template is not a function definition, but the specific instantiation using int is a function definition. This type of instantiation is termed implicit instantiation because the compiler deduces the necessity for making the definition by noting that the program uses a Swap() function with int parameters.

Originally, using implicit instantiation was the only way the compiler generated function definitions from templates, but now C++ allows for explicit instantiation. That means you can instruct the compiler to create a particular instantiation—for example, Swap()—directly. The syntax is to declare the particular variety you want, using the <> notation to indicate the type and prefixing the declaration with the keyword template:

template void Swap(int, int);  // explicit instantiation

A compiler that implements this feature will, upon seeing this declaration, use the Swap() template to generate an instantiation, using the int type. That is, this declaration means “Use the Swap() template to generate a function definition for the int type.” Contrast the explicit instantiation with the explicit specialization, which uses one or the other of these equivalent declarations:

template <> void Swap(int &, int &);  // explicit specialization

template <> void Swap(int &, int &);       // explicit specialization

The difference is that these last two declarations mean “Don’t use the Swap() template to generate a function definition. Instead, use a separate, specialized function definition explicitly defined for the int type.” These prototypes have to be coupled with their own function definitions. The explicit specialization declaration has <> after the keyword template, whereas the explicit instantiation omits the <>.

Caution

It is an error to try to use both an explicit instantiation and an explicit specialization for the same type(s) in the same file, or, more generally, the same translation unit.

Explicit instantiations also can be created by using the function in a program. For instance, consider the following:

template

T Add(T a, T b)    // pass by value

{

    return a + b;

}

...

int m = 6;

double x = 10.2;

cout << Add(x, m) << endl;  // explicit instantiation

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

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

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

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