C++ advanced use enum class instead of enum

   In C++11, the keyword of enumeration is  enum class , that is, class is added after enum, which is different from the "plain" enum of C++98 as follows:

enum class Color { red, green, blue };   

enum Color { red, green, blue };

 Advantages of enum classes

   1: Prevent Namespace Pollution

   2: mandatory type enumeration,

   3: Forward declaration, enum class  supports forward declaration, that is, declares an enumeration type without initializing enumeration members.

Experimental platform: ubutun 20

Experiment code:

#include <iostream>
#include <tuple>


struct Base{};

struct Foo{
  Base base;
  int i;
};


struct Derived1:Base{
  int i;
};


using UserInfo = std::tuple<std::string,std::string,std::size_t>;


enum class UserInfoFileds{uiName,uiEmail,uiReputation};

#if __cplusplus == 201103L
template<typename E>
constexpr typename std::underlying_type<E>::type
   toUtype(E enumerator) noexcept
{
   return static_cast<typename std::underlying_type<E>::type>(enumerator);
}
#elif __cplusplus == 201402L
template<typename E>
constexpr auto  
   toUtype(E enumerator) noexcept
{
   return static_cast<std::underlying_type_t<E>>(enumerator);
}  
#else
template<typename E>
constexpr auto  
   toUtype(E enumerator) noexcept
{
   return static_cast<std::size_t>(enumerator);
}
#endif

int main()
{
   static_assert(sizeof(Base) >=1);
   
   static_assert(sizeof(Foo) == 2* sizeof(int));
   
   
   static_assert(sizeof(Derived1) == sizeof(int));
   
   UserInfo uInfo(std::make_tuple("111", "111",1));
   //auto val = std::get<static_cast<std::size_t>(UserInfoFileds::uiName)>(uInfo);
   auto val = std::get<toUtype(UserInfoFileds::uiName)>(uInfo);
   std::cout << val << std::endl;
   
   std::cout << __cplusplus << std::endl;
   return 0;
   
}

Guess you like

Origin blog.csdn.net/wanglei_11/article/details/130054838