Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does is_convertible<EnumClass, int> return false?

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;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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, either std::declval<From>() can be converted to To using implicit conversions, or both From and To are possibly cv-qualified void), provides the member constant value equal to true. Otherwise value is false.

Values of enum class types (unlike regular enums) require an explicit conversion to perform that conversion; hence, the valued returned by is_convertible_v is correct.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading