Почему в следующем коде нет ошибок компиляции, но clang-tidy
выдаёт ошибку? Компилирую с помощью gcc.
non-constant-expression cannot be narrowed from type
int
tostd::byte
int i = 42;
std::byte byte{i};
Stack Overflow на русском — это сайт вопросов и ответов для программистов. Присоединяйтесь! Регистрация займёт не больше минуты.
Присоединиться к сообществуТип std::byte
определяется как
enum class byte : unsigned char {};
^^^^^^^^^^^^^
Согласно стандарту C++17 (Draft №4714)
(3.8) — Otherwise, if T is an enumeration with a fixed underlying type (10.2), the initializer-list has a single element v, and the initialization is direct-list-initialization, the object is initialized with the value T(v) (8.5.1.3); if a narrowing conversion is required to convert v to the underlying type of T, the program is ill-formed. [ Example:
enum byte : unsigned char { };
byte b { 42 }; // OK
byte c = { 42 }; // error
byte d = byte{ 42 }; // OK; same value as b
byte e { -1 }; // error
Так как у вас используется не константное выражение при прямой инициализации
int i = 42;
std::byte byte{i};
то компилятор выдает сообщение об ошибке.
Также из этого же стандарта
7.4) — from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression whose value after integral promotions will fit into the target type.
Можно было бы написать
const int i = 42;
std::byte byte{i};
error: non-constant-expression cannot be narrowed from type 'int' to 'std::byte' in initializer list [-Wc++11-narrowing]
narrowing conversion of 'i' from 'int' to 'unsigned char' [-Werror=narrowing]
, по-умолчанию он более толерантен, чем прочие компиляторы