Can an enum class be converted to the underlying type?

后端 未结 4 1345
不思量自难忘°
不思量自难忘° 2020-11-28 01:57

Is there a way to convert an enum class field to the underlying type? I thought this would be automatic, but apparently not.

enum class my_field         


        
4条回答
  •  悲&欢浪女
    2020-11-28 02:44

    I find the following function underlying_cast useful when having to serialise enum values correctly.

    namespace util
    {
    
    namespace detail
    {
        template 
        using UnderlyingType = typename std::underlying_type::type;
    
        template 
        using EnumTypesOnly = typename std::enable_if::value, E>::type;
    
    }   // namespace util.detail
    
    
    template >
    constexpr detail::UnderlyingType underlying_cast(E e) {
        return static_cast>(e);
    }
    
    }   // namespace util
    
    enum SomeEnum : uint16_t { A, B };
    
    void write(SomeEnum /*e*/) {
        std::cout << "SomeEnum!\n";
    }
    
    void write(uint16_t /*v*/) {
        std::cout << "uint16_t!\n";
    }
    
    int main(int argc, char* argv[]) {
        SomeEnum e = B;
        write(util::underlying_cast(e));
        return 0;
    }
    

提交回复
热议问题