Can someone improve upon this function of mine? enumToSTLContainerEnumToSTLContainer
is supposed to make a copy of any STL container whose elements are from a specified enum
list.
#include <iostream>
#include <vector>
#include <set>
enum MyEnum {A, B, C, D, E, FirstMyEnum = A, LastMyEnum = E};
template <typename CONTAINER>
CONTAINER enumToSTLContainerEnumToSTLContainer (typename CONTAINER::value_type first, typename CONTAINER::value_type last) {
CONTAINER v;
for (typename std::underlying_type<typename CONTAINER::value_type>::typeint N = first; N <= last; N++)
v.push_back(static_cast<typename CONTAINER::value_type>(N)); // But only works for STL containers with push_back defined.
return v;
}
int main() {
const std::vector<MyEnum> enumVector = enumToSTLContainer<stdEnumToSTLContainer<std::vector<MyEnum>> (FirstMyEnum, LastMyEnum);
for (MyEnum x : enumVector)
std::cout << x << ' '; // 0 1 2 3 4
// const std::set<MyEnum> enumSet = enumToSTLContainer<stdEnumToSTLContainer<std::set<MyEnum>> (FirstMyEnum, LastMyEnum); // won't compile
}
This only works for STL containers with push_back()
defined, and need to specify first and last element of the enum list. It does not work if enum
values are not consecutive.
Perhaps obtaining an initializer_list
using variadic templates would work, which can then return the desired STL container?