isocpp / isocpp/CppCoreGuidelines

Restrict construction of `enum class` values manifestly outside intended usage

Open
#1,854 8 comments 4 reactions 1 assignee View on GitHub

@GabrielDosReis is already working on this.

Since Nov 11, 2021.

Dominant language
CSS
Stars
45.3k
Forks
5.6k
PR merge metrics
No merged PRs in 30d

Description

Consider

enum class TestEnum : uint32_t { One, Two, Three };

int main() {
   TestEnum t { 17 };       // L1
}

Prior to C++17, line L1 was invalid and diagnosed at compile-time. The proposal P0138R0, P0138R1 for C++17 also made that ill-formed. However, the adopted revision P0138R2 -- at the insistence of CWG -- allowed it. That allowance has proven to easy source of mistakes in practice, in more realistic situations such as

enum class AccessType : uint32_t { Read, Write, Execute, };

where no other values of AccessType is expected or tolerated.

The suggestion here is to have a rule that bans the construction of enum class values that are manifestly outside the set expressly indicated in the definition of the enum class. For example,

enum class Foo : int { 
    Apple = 0,
    Banana = 1,
    Cookie = 2,
};

// Allowed
Foo foo { 0 };
Foo foo1 { 1 };
Foo foo2 { 2 };

// Not allowed
Foo foo3 { 3 };

// Allowed
Foo foo { static_cast<Foo>(3) };

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.