In the c++ code below+output, the following is used to iterate over the values of an enum class, say MyEnumClass: (the enum class has contiguous values)
for (const auto& e : MyEnumClass() )
{
// ...
}
In order for the range-based for-loop to work, I had to define the operators ++ and *, as well as begin(MyEnumClass) and end(MyEnumClass).
Although this works, I have not been able to find if it is a legitimate approach. Is it according to the C++ standard? The operators and begin/end I understand, but what is really the meaning here of MyEnumClass()?
I hope there is somebody who can shed some light on this.
Regards, Bertwim
#include <iostream>
enum class MyEnumClass : int
{
BEGIN,
ONE=BEGIN, TWO, THREE, FOUR, // consecutive values!
END
};
auto begin( MyEnumClass )
{
return MyEnumClass::BEGIN;
}
auto end( MyEnumClass )
{
return MyEnumClass::END;
}
MyEnumClass operator++( MyEnumClass& p )
{
return p = static_cast<MyEnumClass>( static_cast<unsigned>( p ) + 1 );
}
MyEnumClass operator*( MyEnumClass p )
{
return p;
}
int main( int, char*[] )
{
for (const auto& e : MyEnumClass() )
{
std::cout << static_cast<int>( e ) << std::endl;
}
}
Compilation and run: (compiler is gcc 11.3.0)
[519] cpptest> g++ main.cpp && ./a.out
0
1
2
3