Logo Ray's Blog
  • Home
  • About
  • News
  • Publications
  • Education
  • More
    Experiences
  • Posts
  • Notes
  • Dark Theme
    Light Theme
Logo Inverted Logo
  • Posts
  • AI
    • Infrastructure
      • Guides On Choosing Deep Learning Server
    • LLM
      • Asksage
    • PyTorch
      • Learning PyTorch Part I
      • Pytorch Distributed Data Parallel With Model Parallel in an HPC Environment
  • Tools
    • NeoVim
    • An Intro to a CLI Password Management: Pass
    • Exercism Cli Shortcut
    • Random Docker/Podman tips
  • HPC
    • ALCF
      • Distributed Training
      • QWen2.5-VL
  • Linux
    • Manage Users in Linux
    • Setup Ubuntu 22.04
  • Embedded Systems
  • Programming
    • C++
      • C++ Enum Pattern
    • Competitive Programming
      • How to Learn Programming
      • Mistakes I Have Made
      • TopCoder
        • HoleCakeCuts topcoder SRM411 div2 level3
        • InfiniteSequence topcoder SRM413 div2 level3
        • StringsAndTabs topcoder SRM412 div2 level3
        • TeleportsNetwork topcoder SRM409 div2 level3
    • Design Patterns
      • Object-Oriented Analysis
      • Object-Oriented Design Principles
    • Python
      • Python Conditional Timeit Decorator
Hero Image
C++ Enum Pattern

Introduction Very often we want to define a set of items to choose from, for example, a set of colors. In C++, we usually can declare enum class Color { Red, Green, Blue }. However, besides using it in a switch statement, we can hardly use it for anything else. For example, if we want to print "Red" for Color::Red, we have to write another function using switch statement, somewhere else. When we want to add a new color, we have to change every places we are using switch. This is obviously an anti-pattern. Occasionally, we want to find how many colors in total, and maybe even want to iterate through them. None of these are supported by C++ enum. In this blog, I want to introduce the Enum Pattern in C++, which supports switch and constains encapsulated member functions, similar to the Enum Class in Java. The idea came from this stackoverflow post.

    Wednesday, January 3, 2018 | 3 minutes Read
    Navigation
    • About
    • News
    • Publications
    • Education
    • Experiences
    Contact me:
    • yren@bnl.gov
    • yhren
    • Yihui (Ray) Ren

    Liability Notice: This blog is for informational and educational purposes only. The content provided here represents personal opinions and is not intended as professional advice. Readers should not rely solely on this information and are responsible for their own actions and decisions. This blog is not liable for any damages or consequences resulting from the use of its content. The views expressed here are my own and do not reflect those of my employer or any funding agencies. © 2017-2025 Yihui Ren. All rights reserved.


    Toha Theme Logo Toha
    © 2017-2025 Yihui Ren. All rights reserved.
    Powered by Hugo Logo