enum to string in modern C++11 / C++14 / C++17 and future C++20

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for enum to string in modern C++11 / C++14 / C++17 and future C++20

📝 enum to string in modern C++: A Comprehensive Guide

Are you tired of struggling to convert enums to strings in modern C++? Look no further! In this blog post, we will explore the new features in C++11, C++14, and C++17, and even give you a sneak peek into what's coming in C++20. 🚀

The Challenge

Enum to string conversion has been a long-standing problem in C++. While there have been numerous solutions proposed over the years, most of them are either not elegant enough or rely on manual mapping. But worry not! We are here to equip you with a solution that utilizes the power of the latest C++ features. 💪

So, What's the Solution?

Let's dive right into an example that demonstrates the solution we're proposing. Here's a snippet of code you can experiment with:

#include <map>
#include <iostream>

struct MyClass
{
    enum class MyEnum : char {
        AAA = -8,
        BBB = '8',
        CCC = AAA + BBB
    };
};

const char* magic(MyClass::MyEnum e)
{
    const std::map<MyClass::MyEnum, const char*> MyEnumStrings {
        { MyClass::MyEnum::AAA, "MyClass::MyEnum::AAA" },
        { MyClass::MyEnum::BBB, "MyClass::MyEnum::BBB" },
        { MyClass::MyEnum::CCC, "MyClass::MyEnum::CCC" }
    };
    auto it = MyEnumStrings.find(e);
    return it == MyEnumStrings.end() ? "Out of range" : it->second;
}

int main()
{
   std::cout << magic(MyClass::MyEnum::AAA) << '\n';
   std::cout << magic(MyClass::MyEnum::BBB) << '\n';
   std::cout << magic(MyClass::MyEnum::CCC) << '\n';
}

In this example, we define an enum MyEnum inside the MyClass struct. To convert the enum values to strings, we use a std::map that maps enum values to their corresponding string representations. The magic function takes an enum value as input and returns the associated string value. Simple as that! ✨

The Benefits

The solution we provided has several advantages:

  • Utilizes modern C++ features: We leverage C++11, C++14, and C++17 features, making our code more concise and elegant.

  • No manual mapping: Unlike other solutions, we avoid a valueless duplication of code or a basic link. Our approach uses a map to automate the enum-to-string mapping process.

  • Compatibility with future standards: We give you a glimpse of C++20 compatibility, ensuring your code remains up-to-date with the latest standards.

Nice-to-Have Features

We understand that a comprehensive solution should cover additional requirements. Here are some nice-to-have features that our solution also supports:

  • Support for enum values starting from a number other than zero.

  • Support for negative enum values.

  • Support for fragmented enum values.

  • Support for class enums (C++11).

  • Support for class enums with any allowed type (C++11).

  • Compile-time conversions to strings or, at least, fast execution at runtime (e.g., std::map is not ideal for performance).

  • constexpr support (C++11, then relaxed in C++14/17/20).

  • noexcept support (C++11).

  • C++17/C++20-friendly code snippets.

Engage and Share!

We hope this guide provides you with a solid understanding of how to convert enums to strings using modern C++. Feel free to share this blog post with other C++ enthusiasts who may be struggling with the same issue. Let's spread the knowledge!

Do you have any other questions or ideas for future blog posts? We'd love to hear from you in the comments section below. Happy coding! 👩‍💻👨‍💻

Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my