Saturday, May 23, 2015

Enumeration Iterator Library (EnumIt)

In the new game I'm making, I've been using enumerations along with constant arrays for some quick configurations and needed a quicker way to iterate through all available enumerations (for example, when loading images who are identified by their enum class value). I created an enum iterator library (EnumIt) which is a single header file. It comes with functions to get an enum's Begin and End iterator and also provides an interface which supports ranged-based for loops. Although very simple, hopefully it will be helpful to someone else. Below is an example which can be found on the github page: https://github.com/Salgat/Enum-Iterator

 #include <iostream>  
 #include <string>  
   
 #include "enumit.hpp"  
   
 enum class SampleId {  
   FIRST,  
   SECOND,  
   THIRD  
 };  
   
 /*  
 enum SampleId {  
   FIRST,  
   SECOND,  
   THIRD  
 };*/  
   
 int main() {  
   for (auto iter = enumit::Begin<SampleId>(); iter != enumit::End<SampleId>(SampleId::THIRD); ++iter) {  
     SampleId entry = *iter;  
     std::cout << "Current SampleId: " << static_cast<int>(entry) << std::endl;  
   }  
   
   for (auto entry : enumit::Iterate<SampleId>(SampleId::THIRD)) {  
     std::cout << "Current SampleId: " << static_cast<int>(entry) << std::endl;  
   }  
   
   return 0;  
 }  

No comments: