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

Then the compiler substitutes int for TT and generates the following class definition:

class HasFriendT

{

...

    friend void counts();

    friend void report<>(HasFriendT &);

};

One specialization is based on TT, which becomes int, and the other is based on HasFriendT, which becomes HasFriendT. Thus, the template specializations counts() and report >() are declared as friends to the HasFriendT class.

The third requirement the program must meet is to provide template definitions for the friends. Listing 14.23 illustrates these three aspects. Note that Listing 14.22 has one count() function that is a friend to all HasFriend classes, whereas Listing 14.23 has two count() functions, one of which is a friend to each of the instantiated class types. Because the count() function calls have no function parameter from which the compiler can deduce the desired specialization, these calls use the count() and count() forms to indicate the specialization. For the calls to report(), however, the compiler can use the argument type to deduce the specialization. You could use the <> form to the same effect:

report >(hfi2);  // same as report(hfi2);

Listing 14.23. tmp2tmp.cpp

// tmp2tmp.cpp -- template friends to a template class

#include

using std::cout;

using std::endl;

// template prototypes

template void counts();

template void report(T &);

// template class

template

class HasFriendT

{

private:

    TT item;

    static int ct;

public:

    HasFriendT(const TT & i) : item(i) {ct++;}

    ~HasFriendT() { ct--; }

    friend void counts();

    friend void report<>(HasFriendT &);

};

template

int HasFriendT::ct = 0;

// template friend functions definitions

template

void counts()

{

    cout << "template size: " << sizeof(HasFriendT) << "; ";

    cout << "template counts(): " << HasFriendT::ct << endl;

}

template

void report(T & hf)

{

    cout << hf.item << endl;

}

int main()

{

    counts();

    HasFriendT hfi1(10);

    HasFriendT hfi2(20);

    HasFriendT hfdb(10.5);

    report(hfi1);  // generate report(HasFriendT &)

    report(hfi2);  // generate report(HasFriendT &)

    report(hfdb);  // generate report(HasFriendT &)

    cout << "counts() output:\n";

    counts();

    cout << "counts() output:\n";

    counts();

    return 0;

}

Here is the output of the program in Listing 14.23:

template size: 4; template counts(): 0

10

20

10.5

counts() output:

template size: 4; template counts(): 2

counts() output:

template size: 8; template counts(): 1

As you can see, counts reports a different template size from counts, demonstrating that each T type now gets its own count() friend.

Unbound Template Friend Functions to Template Classes

The bound template friend functions in the preceding section are template specializations of a template declared outside a class. An int class specialization gets an int function specialization, and so on. By declaring a template inside a class, you can create unbound friend functions for which every function specialization is a friend to every class specialization. For unbound friends, the friend template type parameters are different from the template class type parameters:

template

class ManyFriend

{

...

    template friend void show2(C &, D &);

};

Listing 14.24 shows an example that uses an unbound friend. In it, the function call show2(hfi1, hfi2) gets matched to the following specialization:

void show2 &, ManyFriend &>

          (ManyFriend & c, ManyFriend & d);

Because it is a friend to all specializations of ManyFriend, this function has access to the item members of all specializations. But it only uses access to ManyFriend objects.

Similarly, show2(hfd, hfi2) gets matched to this specialization:

void show2 &, ManyFriend &>

          (ManyFriend & c, ManyFriend & d);

It, too, is a friend to all ManyFriend specializations, and it uses its access to the item member of a ManyFriend object and to the item member of a ManyFriend object.

Listing 14.24. manyfrnd.cpp

// manyfrnd.cpp -- unbound template friend to a template class

#include

using std::cout;

using std::endl;

template

class ManyFriend

{

private:

    T item;

public:

    ManyFriend(const T & i) : item(i) {}

    template friend void show2(C &, D &);

};

template void show2(C & c, D & d)

{

    cout << c.item << ", " << d.item << endl;

}

int main()

{

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

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

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

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