Ben
Ben

Reputation: 1634

C++/CLI: Loop through non-continuous enum

I'm writing a C++/CLI wrapper around a C# library. The libary exposes an enum with non-continuous numeric values (which is something beyond my control, and I would never, never, add this myself, but it needs to be maintained for backwards compatibility)

enum MyCSEnum
{
    Value1 = 1,
    Value2 = 2,
    Value3 = 3,
    Value4 = 5,
    Value5 = 7,
    Value6 = 10,
    Value7 = 13
};

Is there a way to loop over this enum in c++/clr? I can't loop through it numerically, as the underlying values are non-continuous. I know that in C# a range-based loop is possible, but how would this be done in C++/CLI

Upvotes: 0

Views: 948

Answers (2)

David Yaw
David Yaw

Reputation: 27864

Enum::GetValues will return an array containing all the valid enum values. Call that method, and iterate over the result.

Obviously, this requires that the enum in question be a managed enum, not an unmanaged C++ enum. The example enum you showed appears to be an unmanaged enum, but if this is a wrapper of a C# library, then there's probably a managed version of that enum around that you can use.

You could also use Enum::GetValues as a building block to produce a collection of unmanaged enum values within the library, which you can then use to iterate over the unmanaged enum.

Upvotes: 3

Asteroids With Wings
Asteroids With Wings

Reputation: 17454

No.

C++/CLI is an extension to C++, and C++ has no reflection. Reflection would be required for this.

You'll have to maintain an array of "valid" values, and/or use some macro tricks.

Upvotes: 0

Related Questions