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,

有帮助吗?

解决方案

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?

其他提示

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;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top