array indexing (converting to integer) with scoped enumeration

前端 未结 5 423
死守一世寂寞
死守一世寂寞 2020-12-30 02:10

C++11 scoped enumerators (enum class syntax) do not convert to integers so they cannot be used directly as array indexes.

What\'s the best way to get th

5条回答
  •  生来不讨喜
    2020-12-30 02:42

    Why make it harder than it needs to be if your enumeration is consecutive?

    enum class days
    {
            monday,
            tuesday,
            wednesday,
            thursday,
            friday,
            saturday,
            sunday,
            count
    };
    
    ....
    
    const auto buffer_size = static_cast< std::size_t >( days::count );
    char buffer[ buffer_size ];
    buffer[ static_cast< std::size_t >( days::monday ) ] = 'M';
    

    Or if you must use templated functions...

    template< class enumeration >
    constexpr std::size_t enum_count() noexcept
    {
            static_assert( std::is_enum< enumeration >::value, "Not an enum" );
            return static_cast< std::size_t >( enumeration::count );
    }
    
    template< class enumeration >
    constexpr std::size_t enum_index( const enumeration value ) noexcept
    {
         static_assert( std::is_enum< enumeration >::value, "Not an enum" );
         return static_cast< std::size_t >( value )
    }
    
    ...
    
    char buffer[ enum_count< days >() ];
    buffer[ enum_index( days::monday ) ] = 'M';
    

提交回复
热议问题