-
C++11优化 -
污染命名空间
-
强类型
-
回顾
-
非强类型的
Enum -
非强类型的隐式转换
int main() { enum Color { red, black, white }; int redv = red >= 0 ? red : -1; return 0; } -
限制型类型
int main() { enum class Color { red, black, white }; int redv = red >= 0 ? red : -1; return 0; } -
限制型枚举保留能力
int main() { enum class Color { red, black, white }; Color c = Color::red; int redv = static_cast<int>(c) >= 0 ? 0 : -1; return 0; }
-
-
声明
-
回顾
-
c++98 -
C++11enum Color; enum Color {red,black}; int main() { Color c; } -
限制强类型.
enum class Color; enum class Color {red,black}; int main() { Color c; } -
强类型和编译
-
c++98 -
强类型的好处
-
声明并确定类型
#include <iostream> enum class Color:char; enum class Color:char {red,black}; int main() { Color c; std::cout << sizeof(c) << std::endl; }
-
-
非限制的好处
-
前言
-
数字
#include <iostream> #include <string> #include <tuple> using UserInfo = // type alias; see Item 9 std::tuple<std::string, // name std::string, // email std::size_t>; // reputation int main() { UserInfo info("hello","word",1); std::cout << std::get<0>(info) << std::endl; std::cout << std::get<1>(info) << std::endl; std::cout << std::get<2>(info) << std::endl; } -
枚举
#include <iostream> #include <string> #include <tuple> enum Key { name, email, reputation }; using UserInfo = // type alias; see Item 9 std::tuple<std::string, // name std::string, // email std::size_t>; // reputation int main() { UserInfo info("hello","word",1); std::cout << std::get<name>(info) << std::endl; std::cout << std::get<email>(info) << std::endl; std::cout << std::get<reputation>(info) << std::endl; } -
C++11#include <iostream> #include <string> #include <tuple> enum class Key:char { name, email, reputation }; template <typename T> constexpr T E2T(Key k) noexcept { return static_cast<T>(k); } using UserInfo = // type alias; see Item 9 std::tuple<std::string, // name std::string, // email std::size_t>; // reputation int main() { UserInfo info("hello","word",1); std::cout << std::get<E2T<std::size_t>(Key::name)>(info) << std::endl; std::cout << std::get<E2T<std::size_t>(Key::email)>(info) << std::endl; std::cout << std::get<E2T<std::size_t>(Key::reputation)>(info) << std::endl; } -
优化版本
#include <iostream> #include <type_traits> #include <string> #include <tuple> enum class Key { name, email, reputation }; template <typename T> constexpr typename std::underlying_type<T>::type E2T(T k) noexcept { return static_cast<typename std::underlying_type<T>::type>(k); } using UserInfo = // type alias; see Item 9 std::tuple<std::string, // name std::string, // email std::size_t>; // reputation int main() { UserInfo info("hello","word",1); std::cout << std::get<E2T(Key::name)>(info) << std::endl; std::cout << std::get<E2T(Key::email)>(info) << std::endl; std::cout << std::get<E2T(Key::reputation)>(info) << std::endl; }
-
-
总结
C++11 枚举加不加class 的区别
最新推荐文章于 2024-09-05 09:45:27 发布
本文探讨了C++11中枚举特性的改进,包括避免命名空间污染、强类型支持、声明与定义分离等,并对比了C++98的相关特性。通过具体示例展示了这些改进如何提升代码质量和编译效率。
924

被折叠的 条评论
为什么被折叠?



