C++ macro for scoped enums

Posted

Update: In C++ 11 and later, the need for this macro is obsolete due to the introduction of the scoped enum. But I leave this article up on the off-chance someone desires this in an older version of C++.

Here’s a macro I wrote for C++ which I’ve found extremely useful. It creates structures which act just like an enum, but where the value names are inside the scope of the enum.

To avoid values in different enums having the same name, a traditional C++ coding style is to write something like this:

enum Answer
{
  Answer_Right,
  Answer_Wrong,
  Answer_Pending,
};

A naming convention like this is necessary to distinguish from a Direction_Right or a function called Pending(). I wanted something more like C# so I’d be able to use Answer::Right.

#define strenum( name ) \
struct name { enum name##_e; inline operator name##_e&() \
{ return name##_d; } inline operator const name##_e&() const \
{ return name##_d; } name() {} name( const name##_e& i ) : \
name##_d(i) {} name( const int& i ) : \
name##_d(name##_e(i)) {} \
private: name##_e name##_d; }; enum name::name##_e

That’s very ugly code, but to work with it I just put it in a header file and forget what it looks like. Declaration and usage is similar to an enum.

strenum( Material )
{
  Wood = 17,
  Metal,
  Tin = Material::Metal,
};
Material a = Material::Wood;
Material b( a );

The main practical advantage of this is that I can now forget the names of all my enum values and use Intellisense.

Feel free to copy and paset the above into any C++ program you want.