Is it safe to reinterpret_cast an enum class variable to a reference of the underlying type?

后端 未结 3 1059
长情又很酷
长情又很酷 2020-12-03 10:59

I\'ve seen reinterpret_cast used to apply incrementation to enum classes, and I\'d like to know if this usage is acceptable in standard C++.

enu         


        
3条回答
  •  长情又很酷
    2020-12-03 11:39

    It is safe as long as it casts to the exact underlying type of the enum.

    If the underlying type of the enum class changes that ++reinterpret_cast(foo) breaks silently.

    A safer version:

    foo = static_cast(static_cast::type>(foo) + 1);
    

    Or,

    ++reinterpret_cast::type&>(foo);
    

提交回复
热议问题