llvm/llvm-project

[clang-tidy] New check for static_cast of an enum class type

Open

#71.543 geöffnet am 7. Nov. 2023

Auf GitHub ansehen
 (13 Kommentare) (0 Reaktionen) (1 zugewiesene Person)C++ (10.782 Forks)batch import
check-requestclang-tidygood first issue

Repository-Metriken

Stars
 (26.378 Stars)
PR-Merge-Metriken
 (Durchschn. Merge 1T 2h) (1.000 gemergte PRs in 30 T)

Beschreibung

When casting an enum class type using static_cast<T>, this may result in a bug if the type T is not correct. In c++23 we have std::to_underlying which should be used instead. This also is more desirable because if the enum's underlying type is changed later, the casting code is automatically still correct without the need to make the change there, too.

// Fix, must add, if not already present:
#include <utility> // Provides std::to_underlying()


// NOLINTNEXTLINE(performance-enum-size)
enum class EType : int {};

auto main() -> int
{
    // NOLINTNEXTLINE(readability-magic-numbers)
    EType e {42};

    [[maybe_unused]]
    // c++23 and later only

    // Original code:
    // auto i = static_cast<int>(e);
    //          ~~~~~~~~~~~~~~~~
    //          ^ bugprone: use std::to_underlying
    // Fix:
    auto i = std::to_underlying(e);
    return 0;
}

Contributor Guide