User Defined C++11 enum class Default Constructor

后端 未结 3 1344
半阙折子戏
半阙折子戏 2021-02-01 14:22

Is there a way to specify the default constructor of an enum class?

I am using an enum class to specify a set of values which are allowable for

3条回答
  •  忘掉有多难
    2021-02-01 14:54

    An enum class is just a strongly-typed enum; it's not a class. C++11 just reused the existing class keyword to avoid introducing a new keyword that would break compatibility with legacy C++ code.

    As for your question, there is no way to ensure at compile time that a cast involves a proper candidate. Consider:

    int x;
    std::cin >> x;
    auto p = static_cast(x);
    

    This is perfectly legal and there is no way to statically ensure the console user has done the right thing.

    Instead, you will need to check at runtime that the value is valid. To get around this in an automated fashion, one of my co-workers created an enum generator that builds these checks plus other helpful routines given a file with enumeration values. You will need to find a solution that works for you.

提交回复
热议问题