跳到主要內容

發表文章

目前顯示的是 4月, 2020的文章

Stringify C++ Enum Safely

Stringify Enum Safely Sometimes stringifying C/C++ enumerator, or enum , values within its literal names are useful for debugging or logging. In this article, I’ll share how I achieve basic enum stringify and how to do it safely against changes to enum definitions. Basic Idea Given a boring enum Result as follows. enum class Result : int8_t { OK = 0 , FAILED , } ; My usual way to stringify them is using a table, i.e. # define STR(X) #X char const * StringifyResult ( Result res ) { char const * str [ ] = { STR ( OK ) , STR ( FAILED ) , } ; return str [ static_cast < std :: underlying_type_t < Result >> ( res ) ] ; } int main ( ) { printf ( "%s" , StringifyResult ( Result :: OK ) ) ; // print "OK" } It benefits us from simplicity - simply copy’n paste those enum values then decorate them with STR() . Tons of editors can accomplish such editing in a snap. Check Consistency ...