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,
Range-for is as fast as possible since it caches the end iterator[citationprovided], uses pre-increment and only dereferences the iterator once. Then, yes, range-for may be slightly faster, since it's also easier to write there's no reason not to use it (when appropriate).
Range-based for loop in C++It executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.
Basically, range-based loops are faster to be typed (with less characters), while ordinary for loops are more generic. Ordinary loops perform init/condition/effect, whereas foreach loops work directly with iterators. You can model one in the other, but that doesn't make them equivalents.
Range-based for loops work with all standard container types. They're really just a shortcut for certain iterator operations. The type named std::vector<int>::iterator is just another class defined in the standard library.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With