Ask coding questions

← Back to all posts
C++ how to stringify a boolean?
xxpertHacker (865)

Of course, if I wanted a string representation of a boolean, I could do a simple conditional operation:

using std::operator""sv;

auto const string = boolean
    ? "true"sv
    : "false"sv;

but I'm looking for something that I could overload for my own types, ex:

enum class Answer : bool {

std::string std::to_string(
    Answer a
) {
    using std::operator""s;

    return a != Answer::no
        ? "yes"s
        : "no"s;

std::to_string operates on numbers, so it would be odd to overload it for this. Does anyone know of anything that would be well suited for this?