2
\$\begingroup\$

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?

\$\endgroup\$
2
\$\begingroup\$

First of all, you should use std::underlying_type_t<Cont::value_type> instead of int and please don't use UPPER for template parameters (UPPER is mostly for preprocessor, sometimes used for constants and/or static variables), rather use PascalCasing, e.g. Container.

Your implementation looks good to me otherwise, but you know it can only be used with containers with member push_back. If you want to create it from initializer_list, then it would be something different (e.g. EnumRangeInitList). You may find some inspiration in std::integer_sequence.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.