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

One problem is that when you write a template function, it’s not always possible in C++98 to know what type to use in a declaration. Consider this partial example:

template

void ft(T1 x, T2 y)

{

    ...

    ?type? xpy = x + y;

    ...

}

What should the type for xpy be? We don’t know in advance how ft() might be used. The proper type might be T1 or T2 or some other type altogether. For example, T1 could be double and T2 could be int, in which case the type of the sum is double. Or T1 could be short and T2 could be int, in which case the type of the sum is int. Or suppose T1 is short and T2 is char. Then addition invokes automatic integer promotions, and the resultant type is int. Also the + operator can be overloaded for structures and classes, complicating the options further. Therefore, in C++98 there is no obvious choice for the type of xpy.

The decltype Keyword (C++11)

The C++11 solution is a new keyword: decltype. It can be used in this way:

int x;

decltype(x) y;   // make y the same type as x

The argument to decltype can be an expression, so in the ft() example, we could use this code:

decltype(x + y) xpy;  // make xpy the same type as x + y

xpy = x + y;

Alternatively, we could combine these two statements into an initialization:

decltype(x + y) xpy = x + y;

So we can fix the ft() template this way:

template

void ft(T1 x, T2 y)

{

    ...

    decltype(x + y) xpy = x + y;

    ...

}

The decltype facility is a bit more complex than it might appear from these examples. The compiler has to go through a checklist to decide on the type. Suppose we have the following:

decltype(expression) var;

Here’s a somewhat simplified version of the list.

Stage 1: If expression is an unparenthesized identifier (that is, no additional parentheses), then var is of the same type as the identifier, including qualifiers such as const:

double x = 5.5;

double y = 7.9;

double ℞ = x;

const double * pd;

decltype(x) w;       // w is type double

decltype(rx) u = y;  // u is type double &

decltype(pd) v;      // v is type const double *

Stage 2: If expression is a function call, then var has the type of the function return type:

long indeed(int);

decltype (indeed(3)) m; // m is type int

Note

The call expression isn’t evaluated. In this case, the compiler examines the prototype to get the return type; there’s no need to actually call the function.

Stage 3: If expression is an lvalue, then var is a reference to the expression type. This might seem to imply that earlier examples such as w should have been reference types, given that w is an lvalue. However, keep in mind that case was already captured in Stage 1. For this stage to apply, expression can’t be an unparenthesized identifier. So what can it be? One obvious possibility is a parenthesized identifier:

double xx = 4.4;

decltype ((xx)) r2 = xx;  // r2 is double &

decltype(xx) w = xx;      // w is double (Stage 1 match)

Incidentally, parentheses don’t change the value or lvaluedness of an expression. For example, the following two statements have the same effect:

xx = 98.6;

(xx) = 98.6;  // () don't affect use of xx

Stage 4: If none of the preceding special cases apply, var is of the same type as expression:

int j = 3;

int &k = j

int &n = j;

decltype(j+6) i1;   // i1 type int

decltype(100L) i2;  // i2 type long

decltype(k+n) i3;   // i3 type int;

Note that although k and n are references, the expression k+n is not a reference; it’s just the sum of two ints, hence an int.

If you need more than one declaration, you can use typedef with decltype:

template

void ft(T1 x, T2 y)

{

    ...

    typedef decltype(x + y) xytype;

    xytype xpy = x + y;

    xytype arr[10];

    xytype & rxy = arr[2];   // rxy a reference

    ...

}

Alternative Function Syntax (C++11 Trailing Return Type)

The decltype mechanism by itself leaves another related problem unsolved. Consider this incomplete template function:

template

?type? gt(T1 x, T2 y)

{

    ...

    return x + y;

}

Again, we don’t know in advance what type results from adding x and y. It might seem that we could use decltype(x + y) for the return type. Unfortunately, at that point in the code, the parameters x and y have not yet been declared, so they are not in scope (visible and usable to the compiler). The decltype specifier has to come after the parameters are declared. To make this possible, C++11 allows a new syntax for declaring and defining functions. Here’s how it works using built-in types. The prototype

double h(int x, float y);

can be written with this alternative syntax:

auto h(int x, float y) -> double;

This moves the return type to after the parameter declarations. The combination -> double is called a trailing return type. Here, auto, in another new C++11 role, is a placeholder for the type provided by the trailing return type. The same form would be used with the function definition:

auto h(int x, float y) -> double

{/* function body */};

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

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

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

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