Skip to main content
6 of 6
Rollback to Revision 4
Jamal
  • 34.9k
  • 13
  • 133
  • 237

Enum list to STL container

Can someone improve upon this function of mine? EnumToSTLContainer 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 EnumToSTLContainer (typename CONTAINER::value_type first, typename CONTAINER::value_type last) {
    CONTAINER v;
    for (int 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<std::vector<MyEnum>> (FirstMyEnum, LastMyEnum);
    for (MyEnum x : enumVector)
        std::cout << x << ' ';  // 0 1 2 3 4
//  const std::set<MyEnum> enumSet = EnumToSTLContainer<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?

prestokeys
  • 1.4k
  • 10
  • 19