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?
سؤال
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 begin
and end
methods returning an iterator type.
Example:
int arr[] = { 1, 2, 3, 4 };
for (int cur : arr)
std::cout << cur << std::endl;