Created
June 20, 2016 05:22
-
-
Save DanielUranga/bd52a28a56f2e97ef672b971a8208ab1 to your computer and use it in GitHub Desktop.
Typed key array
This file contains 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
#include <iostream> | |
#include <iterator> | |
#include <type_traits> | |
enum EnumA { | |
A, | |
B, | |
C, | |
D, | |
EnumALast | |
}; | |
enum EnumB { | |
Cero, | |
Uno, | |
Dos, | |
Tres, | |
Cuatro, | |
EnumBLast | |
}; | |
template <typename TKey, typename TValue, unsigned int N> | |
class ArrayWithEnumAsKey { | |
static_assert(std::is_enum<TKey>::value, "Invalid argument (not enum)"); | |
public: | |
class Iterator : public std::iterator<std::input_iterator_tag, TKey, std::ptrdiff_t, TValue*, TValue&> { | |
public: | |
Iterator(TValue* x) :p(x) {} | |
Iterator(const Iterator& mit) : p(mit.p) {} | |
Iterator& operator++() {++p; return *this;} | |
//Iterator operator++(int) {Iterator tmp(*this); operator++();return tmp;} | |
bool operator==(const Iterator& rhs) {return p==rhs.p;} | |
bool operator!=(const Iterator& rhs) {return p!=rhs.p;} | |
TValue& operator*() {return *p;} | |
private: | |
TValue *p; | |
}; | |
TValue& operator[](TKey idx) { | |
return arr[idx]; | |
}; | |
const TValue& operator[](TKey idx) const { | |
return arr[idx]; | |
}; | |
const size_t size() { | |
return N; | |
} | |
const Iterator begin() { | |
return Iterator(arr); | |
} | |
const Iterator end() { | |
return Iterator(arr+N); | |
} | |
private: | |
TValue arr[N]; | |
}; | |
int main() { | |
ArrayWithEnumAsKey<EnumB, std::string, EnumBLast> test1; | |
std::string hola = "test"; | |
for (auto iter = test1.begin(); iter != test1.end(); ++iter) { | |
*iter = hola; | |
hola += "."; | |
} | |
for (auto elem : test1) { | |
std::cout << elem << std::endl; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment