假设我们有
enum class Month {jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec};
Run Code Online (Sandbox Code Playgroud)
每个值都是一个0到11的整数。然后,我希望Month类型的变量仅保存这些枚举值。因此,这是创建变量的唯一可行方法:
Month m = Month::may;
Run Code Online (Sandbox Code Playgroud)
但是以下是该语言允许的其他一些方式:
Month m1 = Month(12345);
Month m2 = static_cast<Month>(12345);
Run Code Online (Sandbox Code Playgroud)
这有点令人失望。我如何只允许第一种方式?或者人们如何应对C ++中的穷举枚举?
我如何只允许第一种方式?
枚举是不可能的。
如果您想要一个不能从(可能是无效的)值显式转换的白痴证明“枚举”,则可以使用完整类而不是枚举。不幸的是,这涉及一些样板:
struct Month {
constexpr int value() noexcept { return v; }
static constexpr Month jan() noexcept { return 0; };
static constexpr Month feb() noexcept { return 1; };
static constexpr Month mar() noexcept { return 2; };
static constexpr Month apr() noexcept { return 3; };
static constexpr Month may() noexcept { return 4; };
static constexpr Month jun() noexcept { return 5; };
static constexpr Month jul() noexcept { return 6; };
static constexpr Month aug() noexcept { return 7; };
static constexpr Month sep() noexcept { return 8; };
static constexpr Month oct() noexcept { return 9; };
static constexpr Month nov() noexcept { return 10; };
static constexpr Month dec() noexcept { return 11; };
private:
int v;
constexpr Month(int v) noexcept: v(v) {}
};
Run Code Online (Sandbox Code Playgroud)