Search code examples
c++templatessfinaetemplate-specialization

Function that only accepts enumeration types


Man, I can't stand this damn templates no mo'

So suppose I have this function...

void sort(vector<int>& vec)
{
    // stuff
}

How can I make that function accept vectors of all enumeration types without overloading it 10 goddamn times?

I don't know much about templates but was thinking about doing something like this... (which gave me the error: type name is not allowed)

template<typename T, std::enable_if_t<std::is_enum<T>>>
void sort(vector<T>& vec)
{
    // stuff
}

Solution

  • Just if you use fresh C++ (what I recommend if possible). There is a working example using concepts (c++20). Just tested at gcc 10

    #include <type_traits>
    #include <vector>
    #include <concepts>
    
    template<typename T> requires std::is_enum<T>::value
    void sort(std::vector<T> & vec)
    {
            // stuff
    }
    
    int main()
    {
            enum Mew
            {
                neat,
                ugly
            };
    
            std::vector<Mew> v;
            sort(v);               //works
    
            std::vector<int> v_int;
            sort(v_int);           //error here
    
            return 0;
    }