Home > Backend Development > C++ > How to Automatically Convert C Enums to Strings Without Modifying Source Code?

How to Automatically Convert C Enums to Strings Without Modifying Source Code?

Susan Sarandon
Release: 2024-12-17 18:51:16
Original
417 people have browsed it

How to Automatically Convert C   Enums to Strings Without Modifying Source Code?

How to Convert C Enums to Strings

When working with named C enums, you may encounter scenarios where converting an enum value to its corresponding string representation is necessary. While several approaches exist for this conversion, this article addresses a specific query regarding generating functions for converting all enums in a project to strings without modifying the source code.

X-Macros: A Comprehensive Solution

The recommended approach involves utilizing X-macros. An example implementation is presented below:

#include <iostream>

enum Colours {
#   define X(a) a,
#   include "colours.def"
#   undef X
    ColoursCount
};

char const* const colours_str[] = {
#   define X(a) #a,
#   include "colours.def"
#   undef X
    0
};

std::ostream&amp; operator<<(std::ostream&amp; os, enum Colours c)
{
    if (c >= ColoursCount || c < 0) return os << "???";
    return os << colours_str[c];
}

int main()
{
    std::cout << Red << Blue << Green << Cyan << Yellow << Magenta << std::endl;
}
Copy after login

In the colours.def file, define the enums as follows:

X(Red)
X(Green)
X(Blue)
X(Cyan)
X(Yellow)
X(Magenta)
Copy after login

This method provides a flexible way to generate conversion functions for all enums in your project without making any modifications to your source code.

Customizable String Generation

Alternatively, you can opt for a method that allows for customization of the generated string representations. The following code snippet illustrates how to achieve this:

#define X(a, b) a,
#define X(a, b) b,

X(Red, "red")
X(Green, "green")
// etc.
Copy after login

This approach provides greater control over the generated strings and can be particularly useful when you need specific customizations for your application.

The above is the detailed content of How to Automatically Convert C Enums to Strings Without Modifying Source Code?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template