Home > Net >  How to suppress unscoped enum warning in custom namespace?
How to suppress unscoped enum warning in custom namespace?

Time:10-28

I have some enums inside of my own namespace, yet I still get that annoying warning about "pollution in the global namespace". Why am I getting this error since they aren't even in the global namespace? How could I get rid of this warning? The exact warning is:

C26812, The enum type 'Adventure_Game::itemType' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).

I have the enum declarations in my namespace inside the header file like this:

namespace Adventure_Game {

    enum itemType { Consumable, Key };
    enum equipType { Unarmed, Weapon, Shield, Armor };

    struct invItem { string name = "(name)", desc = "(desc)"; itemType type; unsigned int amount = 0; float value = 0.0f; };
    struct invEquip { string name = "(name)", desc = "(desc)"; equipType type; float low = 0.0f, high = 1.0f, weight = 0.0f, value = 0.0f; bool equip = false; };

}

I tried using enum classes too, but I don't want to use them in this case because it would break everything, and I'd have to use static casts everywhere and it would just be a mess. I would really appreciate help on dealing with this annoying warning.

Thanks :)

CodePudding user response:

The MSVC warning C26812 is not from the C/C compiler. It's coming from the Static Code Analysis (/analyze) feature and specifically from the C Core Guidelines Checker.

The "recommended solution" that the checker is telling you about is to use C 11 strongly typed enumerations. That said, you can just suppress the warning as the C Core Guidelines are just recommendations.

#pragma warning(disable : 4619 4616 26812)
// C4619/4616 #pragma warning warnings
// 26812: The enum type 'x' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).

You could also create a custom ruleset through the UI mentioned on Microsoft Docs if you wanted, but most of the other rules are all sensible so I find the single warning suppression to be the easiest path.

  • Related