5

A compiler error occurs when I try to compile the following code:

for(binary_instructions_t &inst: BinaryInstructions){


}

BinaryInstructions is this enum class:

typedef unsigned int binary_instructions_t;

enum class BinaryInstructions : binary_instructions_t
{
    END_OF_LAST_INSTR = 0x0,

    RESET,
    SETSTEP,
    START,
    STOP,

    ADD,
    REMOVE,
};

Should I be allowed to "do a" range based for loop using the items inside an enum class? Or have I subtly misunderstood in that range based for loops are for searching the contents of an array and not stuff like enum classes?

I have also tried: Creating an instance and searching within the instance:

BinaryInstructions bsInstance;
for(binary_instructions_t &inst : bsInstance){


}

But no cigar... Thanks in advance,

2 Answers 2

8

The range-based for loop needs a collection, like an array or a vector. The enum class isn't a collection.

However, it's C++, so there's a workaround. See: Allow for Range-Based For with enum classes?

Sign up to request clarification or add additional context in comments.

1 Comment

that sweet! I love that implementation. Much cleaner than the casting to int solution I would have used.
0

Range-based for-loops are a mechanism for easy iteration over a list of elements. A 'list of elements' can be a plain array or an instance of a class that implements the beginand end methods returning an iterator type.

Example:

int arr[] = { 1, 2, 3, 4 };
for (int cur : arr)
   std::cout << cur << std::endl;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.