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

To understand what this does, imagine the specialization produced if you declare an object of a particular type:

HasFriend hf;

The compiler would replace the template parameter T with int, giving the friend declaration this form:

class HasFriend

{

    friend void report(HasFriend &); // bound template friend

    ...

};

That is, report() with a HasFriend parameter becomes a friend to the HasFriend class. Similarly, report() with a HasFriend parameter would be an overloaded version of report() that is a friend to the HasFriend class.

Note that report() is not itself a template function; it just has a parameter that is a template. This means that you have to define explicit specializations for the friends you plan to use:

void report(HasFriend &) {...}; // explicit specialization for short

void report(HasFriend &) {...};   // explicit specialization for int

Listing 14.22 illustrates these points. The HasFriend template has a static member ct. Note that this means that each particular specialization of the class has its own static member. The counts() method, which is a friend to all HasFriend specializations, reports the value of ct for two particular specializations: HasFriend and HasFriend. The program also provides two report() functions, each of which is a friend to one particular HasFriend specialization.

Listing 14.22. frnd2tmp.cpp

// frnd2tmp.cpp -- template class with non-template friends

#include

using std::cout;

using std::endl;

template

class HasFriend

{

private:

    T item;

    static int ct;

public:

    HasFriend(const T & i) : item(i) {ct++;}

    ~HasFriend()  {ct--; }

    friend void counts();

    friend void reports(HasFriend &); // template parameter

};

// each specialization has its own static data member

template

int HasFriend::ct = 0;

// non-template friend to all HasFriend classes

void counts()

{

    cout << "int count: " << HasFriend::ct << "; ";

    cout << "double count: " << HasFriend::ct << endl;

}

// non-template friend to the HasFriend class

void reports(HasFriend & hf)

{

    cout <<"HasFriend: " << hf.item << endl;

}

// non-template friend to the HasFriend class

void reports(HasFriend & hf)

{

    cout <<"HasFriend: " << hf.item << endl;

}

int main()

{

    cout << "No objects declared: ";

    counts();

    HasFriend hfi1(10);

    cout << "After hfi1 declared: ";

    counts();

    HasFriend hfi2(20);

    cout << "After hfi2 declared: ";

    counts();

    HasFriend hfdb(10.5);

    cout << "After hfdb declared: ";

    counts();

    reports(hfi1);

    reports(hfi2);

    reports(hfdb);

    return 0;

}

Some compilers will warn about using a non-template friend. Here is the output of the program in Listing 14.22:

No objects declared: int count: 0; double count: 0

After hfi1 declared: int count: 1; double count: 0

After hfi2 declared: int count: 2; double count: 0

After hfdb declared: int count: 2; double count: 1

HasFriend: 10

HasFriend: 20

HasFriend: 10.5

Bound Template Friend Functions to Template Classes

You can modify the preceding example by making the friend functions templates themselves. In particular, you can set things up for bound template friends, so each specialization of a class gets a matching specialization for a friend. The technique is a bit more complex than for non-template friends and involves three steps.

For the first step, you declare each template function before the class definition:

template void counts();

template void report(T &);

Next, you declare the templates again as friends inside the function. These statements declare specializations based on the class template parameter type:

template

class HasFriendT

{

...

    friend void counts();

    friend void report<>(HasFriendT &);

};

The <> in the declarations identifies these as template specializations. In the case of report(), the <> can be left empty because the following template type argument can be deduced from the function argument:

HasFriendT

You could, however, use this instead:

report >(HasFriendT &)

However, the counts() function has no parameters, so you have to use the template argument syntax () to indicate its specialization. Note, too, that TT is the parameter type for the HasFriendT class.

Again, the best way to understand these declarations is to imagine what they become when you declare an object of a particular specialization. For example, suppose you declare this object:

HasFriendT squack;

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

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

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

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