Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
josuttis_nm_c20_the_complete_guide.pdf
Скачиваний:
44
Добавлен:
27.03.2023
Размер:
5.85 Mб
Скачать

23.3 Safe Comparisons of Integral Values and Sizes

687

23.3 Safe Comparisons of Integral Values and Sizes

Comparing integral values of different types is more complex than expected. This section describes two new features of C++20 for dealing with this problem:

Utilities for integral comparisons

std::ssize()

23.3.1 Safe Comparisons of Integral Values

Comparing and converting numbers, even of different numeric types, should be a trivial task. Unfortunately, it is not. Almost all programmers have seen warnings about code doing this. These warnings have a good reason: because of implicit conversions, we may write unsafe code without noticing it.

For example, most of the time we expect that a simple x < y just works. Consider the following example:1

int x = -7; unsigned y = 42;

if (x < y) ... // OOPS: false

The reason for this behavior is that when comparing a signed with an unsigned value by rule (from the programming language C), the signed value is converted into an unsigned type, which makes it a big positive integral value.

To fix this code, you have to write the following instead:

if (x < static_cast<int>(y)) ... // true

Other problems can occur if we compare small integral values with large integral values.

C++20 now provides functions for safe integral comparisons in <utility>. Table Safe integral comparison functions lists these functions. You can use them to simply write:

if (std::cmp_less(x, y)) ...

// true

This integral comparison is always safe.

 

 

 

 

 

 

 

Constant

 

Template

 

std::cmp_equal(x, y)

 

Yields whether x is equal to y

 

std::cmp_not_equal(x, y)

 

Yields whether x is not equal to y

 

std::cmp_less(x, y)

 

Yields whether x is less than y

 

std::cmp_less_equal(x, y)

 

Yields whether x is less than or equal to y

 

std::cmp_greater(x, y)

 

Yields whether x is greater than y

 

std::cmp_greater_equal(x, y)

Yields whether x is greater than or equal to y

 

std::in_range<T>(x)

 

Yields whether x is a valid value for type T

Table 23.1. Safe integral comparison functions

1 Thanks to Federico Kircheis for pointing out this example in http://wg21.link/p0586r2.