13

I am writing a lot of parser code where string_view excels, and have become fond of the type. I recently read ArthurO'Dwyer's article std::string_view is a borrow type, where he concludes that string_view (and other 'borrow types') are fine to use as long as they "... appear only as function parameters and for-loop control variables." (with a couple of exceptions).

However, I have lately started to use string_view as return value for functions that convert enum to string (which I use a lot), like this Compiler Explorer:

#include <iostream>
#include <string>
#include <array>
#include <algorithm>

enum class Color
{
    red, green, blue, yellow,
    last // Must be kept last
};
constexpr std::string_view toString(Color color); 

// The rest would normally be in a .cpp file

using cts = std::pair<Color, std::string_view>;
constexpr std::array colorNames = {cts{Color::red, "red color"},
                            cts{Color::green, "green color"},
                            cts{Color::blue, "blue color"},
                            cts{Color::yellow, "yellow color"}};

static_assert(colorNames.size() == static_cast<size_t>(Color::last));

constexpr std::string_view toString(Color color)
{
    // Normally calling a library function (which also checks for no match), instead of this:
    return std::ranges::find(colorNames, color, &cts::first)->second;
}

int main()
{
    auto s1 = toString(Color::green);
    auto s2 = toString(Color::blue);

    std::cout << s1 << ' ' << s2 << std::endl;
}

The reasons I have for doing it this way are:

  1. By having it stored in an array as string_view, I can make the entire table constexpr.
  2. By returning the string_view directly, there is no need of converting the string representation, so the entire function can be constexpr, or at least avoid creating unnecessary strings even when called with a non-constexpr parameter.
  3. A side effect of having the table constexpr is that I can use static_assert to check that all elements of the enum are in the table, which is really great for catching additions to the enum. I really don't like having to put the 'last' enum value in there, but I don't see a better solution.

So my question is really, is returning the string_view this way unsafe (or UB) in any way, or can I keep on doing this with good conscience?

Alternatively, is there a better (faster/safer) way of solving this general problem of enum-to-string?

Addition: After reading G. Sliepen's very good answer, I'd like to add upon my comment to his answer: I often have the opposite function as well, e.g.:

constexpr Color fromString(string_view str)
{
  // No-match handling omitted
  return std::ranges::find(colorNames, color, &cts::second)->first;
}

In those situations I really do need the translation as a separate table so that it can be used by both functions. But in many other cases, the function containing a switch statement is the simplest and best.

1 Answer 1

12

is returning the string_view this way unsafe (or UB) in any way, or can I keep on doing this with good conscience?

Yes. The way you use it is perfectly ok. The string_view returned by your toString function forms a view on data that will remain intact until the program terminates.

Alternatively, is there a better (faster/safer) way of solving this general problem of enum-to-string?

You could make a constexpr function with a switch-statement inside it, like so:

constexpr std::string_view toString(Color color)
{
    switch (color) {
    case Color::red:   return "red";
    case Color::green: return "green";
    ...
    }
}

There should be no difference in efficiency if the function is evaluated at compile-time. But the compiler can check if you added case-statements for all the possible Colors, and if not it will give a warning. There's also no need for a Color::last this way.

Keeping both the enum and the std::array or switch-statement in sync can be annoying, especially if you have lots of enumeration values. X macros might help here.

5
  • 1
    Yes, this is a good option. I didn't mention it in my original post, but in my code, the enum-string_view arrays are often used the other way too, e.g. in a function like Color fromString(string_view str), which matches the second element of the pair to return the first. To handle this, I need the array, and not only a switch statement in the function. But otherwise you are right that a simple switch function (still returning string_view) may sometimes be better. Commented Oct 23, 2021 at 8:37
  • You can still use a chain of if-else statements instead of a switch to handle fromString(). But if that can't be evaluated at compile time (because str comes from some external input), it's better to use something like a std::unordered_map than a std::array if you have a large number of colors.
    – G. Sliepen
    Commented Oct 23, 2021 at 8:57
  • But if using if-else (or similar) inside the fromString function, I would suddenly need to have the enum-string_view info duplicated, in both the toString and fromString function - and that is something I would never do. Commented Oct 23, 2021 at 9:10
  • 1
    Sure, although that's where X macros could help as well. You can just have a single std::array that maps enum values to strings, but searching that at run time is potentially going to be slow. Another alternative is to use something like a Boost::Bimap. Or perhaps this Magic Enum library is something you could use. Maybe with C++23 we will get langauge support for reflection.
    – G. Sliepen
    Commented Oct 23, 2021 at 9:20
  • I guess X macros could help, but we have a pretty strict "no macros" standard (which I support) in my company. I am aware of the possibilities that will open up with reflection, and really, really hope I can use that in a couple of years. Those two others look very interesting though, thanks :-) Commented Oct 23, 2021 at 9:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.