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

Listing 14.20. tempmemb.cpp

// tempmemb.cpp -- template members

#include

using std::cout;

using std::endl;

template

class beta

{

private:

    template   // nested template class member

    class hold

    {

    private:

        V val;

    public:

        hold(V v  = 0) : val(v) {}

        void show() const { cout << val << endl; }

        V Value() const { return val; }

    };

    hold q;             // template object

    hold n;           // template object

public:

    beta( T t, int i) : q(t), n(i) {}

    template   // template method

    U blab(U u, T t) { return (n.Value() + q.Value()) * u / t; }

    void Show() const { q.show(); n.show();}

};

int main()

{

    beta guy(3.5, 3);

    cout << "T was set to double\n";

    guy.Show();

    cout << "V was set to T, which is double, then V was set to int\n";

    cout << guy.blab(10, 2.3) << endl;

    cout << "U was set to int\n";

    cout << guy.blab(10.0, 2.3) << endl;

    cout << "U was set to double\n";

    cout << "Done\n";

    return 0;

}

The hold template is declared in the private section in Listing 14.20, so it is accessible only within the beta class scope. The beta class uses the hold template to declare two data members:

hold q;             // template object

hold n;           // template object

n is a hold object based on the int type, and the q member is a hold object based on the T type (the beta template parameter). In main(), the following declaration makes T represent double, making q type hold:

beta guy(3.5, 3);

The blab() method has one type (U) that is determined implicitly by the argument value when the method is called and one type (T) that is determined by the instantiation type of the object. In this example, the declaration for guy sets T to type double, and the first argument in the method call in the following sets U to type int, matching the value 10:

cout << guy.blab(10, 2.5) << endl;

Thus, although the automatic type conversions brought about by mixed types cause the calculation in blab() to be done as type double, the return value, being type U, is an int. Hence, it is truncated to 28, as the following program output shows:

T was set to double

3.5

3

V was set to T, which is double, then V was set to int

28

U was set to int

28.2609

U was set to double

Done

Note that replacing 10 with 10.0 in the call to guy.blab() causes U to be set to double, making the return type double, which is reflected in 28.2609 being displayed.

As mentioned previously, the type of the second parameter is set to double by the declaration of the guy object. Unlike the first parameter, then, the type of the second parameter is not set by the function call. For instance, the following statement would still implement blah() as blah(int, double), and the 3 would be converted to type double by the usual function prototype rules:

cout << guy.blab(10, 3) << endl;

You can declare the hold class and blah method in the beta template and define them outside the beta template. However, sufficiently old compilers won’t accept template members at all, and others that accept them as shown in Listing 14.20 don’t accept definitions outside the class. However, if your compiler is willing and able, here’s how defining the template methods outside the beta template would look:

template

class beta

{

private:

    template   // declaration

    class hold;

    hold q;

    hold n;

public:

    beta( T t, int i) : q(t), n(i) {}

    template   // declaration

    U blab(U u, T t);

    void Show() const { q.show(); n.show();}

};

// member definition

template

  template

    class beta::hold

    {

    private:

        V val;

    public:

        hold(V v  = 0) : val(v) {}

        void show() const { std::cout << val << std::endl; }

        V Value() const { return val; }

    };

// member definition

template

  template

    U beta::blab(U u, T t)

    {

       return (n.Value() + q.Value()) * u / t;

    }

The definitions have to identify T, V, and U as template parameters. Because the templates are nested, you have to use the

template

  template

syntax instead of this syntax:

template

The definitions also must indicate that hold and blab are members of the beta class, and they use the scope-resolution operator to do so.

Templates As Parameters

You’ve seen that a template can have type parameters, such as typename T, and non-type parameters, such as int n. A template can also have a parameter that is itself a template. Such parameters are yet another template feature addition that is used to implement the STL.

Listing 14.21 shows an example that begins with these lines:

template

class Crab

The template parameter is template class Thing. Here template class is the type, and Thing is the parameter. What does this imply? Suppose you have this declaration:

Crab legs;

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

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

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

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