I don't understand why std::is_convertible_v<EnumClass, int>
returns false in this example, especially given that static_cast<int>(enumClassValue)
works correctly.
#include <iostream>
enum Enum {X = 5};
enum class EnumClass {X = 5};
int main() {
Enum enumValue = Enum::X;
std::cout << static_cast<int>(enumValue) << std::endl;
std::cout << std::is_convertible_v<Enum, int> << std::endl;
EnumClass enumClassValue = EnumClass::X;
std::cout << static_cast<int>(enumClassValue) << std::endl;
std::cout << std::is_convertible_v<EnumClass, int> << std::endl;
return 0;
}
std::is_convertible_v<From, To>
returns true
if a value of type From
is implicitly convertible to type To
.
https://en.cppreference.com/w/cpp/types/is_convertible
If the imaginary function definition
To test() { return std::declval<From>(); }
is well-formed, (that is, eitherstd::declval<From>()
can be converted toTo
using implicit conversions, or bothFrom
andTo
are possibly cv-qualifiedvoid
), provides the member constant value equal totrue
. Otherwise value isfalse
.
Values of enum class
types (unlike regular enum
s) require an explicit conversion to perform that conversion; hence, the valued returned by is_convertible_v
is correct.