Created
December 24, 2013 03:40
-
-
Save DigiTec/8108514 to your computer and use it in GitHub Desktop.
So I was thinking about range based for loops and I saw some partial code for one that worked on an enum. This adds more generic behavior to that enum and allows self selection of the start/end of the enumeration and ensures that the range you are using is increasing from first to last. Since this is pretty much a working piece of code and there…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// RangeBasedFor.cpp : Defines the entry point for the console application. | |
// | |
#include "stdafx.h" | |
template <typename T, T first = T::First, T last = T::Last> | |
class Enum | |
{ | |
static_assert(first <= last, "foo"); | |
public: | |
class Iterator | |
{ | |
public: | |
Iterator( int value ) : | |
m_value( value ) | |
{ } | |
T operator*( void ) const | |
{ | |
return (T)m_value; | |
} | |
void operator++( void ) | |
{ | |
++m_value; | |
} | |
bool operator!=( Iterator rhs ) | |
{ | |
return m_value != rhs.m_value; | |
} | |
private: | |
int m_value; | |
}; | |
}; | |
template<typename T, T first, T last> | |
typename Enum<T,first,last>::Iterator begin(const Enum<T,first,last>& foo) | |
{ | |
return typename Enum<T,first,last>::Iterator((int)first); | |
} | |
template<typename T, T first, T last> | |
typename Enum<T,first,last>::Iterator end(const Enum<T,first,last>& foo) | |
{ | |
return typename Enum<T,first,last>::Iterator(((int)last)+1); | |
} | |
enum class ChessPieces | |
{ | |
Pawn, | |
Rook, | |
Knight, | |
Bishop, | |
Queen, | |
King, | |
First = Pawn, | |
Last = King | |
}; | |
enum class Foo | |
{ | |
Bar, | |
Baz, | |
Last=Baz | |
}; | |
int wmain(int argc, wchar_t* argv[]) | |
{ | |
for (const ChessPieces& c : Enum<ChessPieces>()) | |
{ | |
wprintf(L"%d\n", (int)c); | |
} | |
for (const Foo& foo : Enum<Foo, Foo::Bar>()) | |
{ | |
} | |
for (const Foo& foo : Enum<Foo, Foo::Baz, Foo::Bar>()) | |
{ | |
} | |
getchar(); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment