-1

Suppose we have enum with implemented operator<< converting enum value to string. Is it possible to call this operator during string construction or something similar? My current approach uses std::stringstream calling << on enum and extracting string from std::stringstream. Is there any other way? Using std::cout << is not an option.

Example code:

enum class Status {
    OK,
    ERROR
}

::std::ostream& operator<<(::std::ostream& os, Status status)
{
    switch (status) {
        case Status::OK:
            return os << "OK";
        case Status::ERROR:
            return os << "ERROR";
}

Usage:

Status s = Status::OK;
std::stringstream stream;
stream << s;
std::string statusString = s.str().c_str();
krizajb
  • 1,715
  • 3
  • 30
  • 43
  • You could always make a `std::map` then you could use this for both retrieving the string and defining your `operator<<` if you want `std::map statuses{ {Status::OK, "OK"}, {Status::ERROR, "ERROR"} };` – Cory Kramer Jun 24 '15 at 11:46
  • possible duplicate of [enum to string in modern C++ and future C++17](http://stackoverflow.com/questions/28828957/enum-to-string-in-modern-c-and-future-c17) – Captain Giraffe Jun 24 '15 at 11:47
  • 1
    You are missing default case, but you are doing it ok. Or the trick with std::map – BЈовић Jun 24 '15 at 11:55

1 Answers1

0

Unfortunately, here is no any elegant solution as you want.

If we only could, we might use a user defined conversion but it needs to be a non-static member function which is impossible with enums.

But you may always use argument-dependent lookup like you do with your operator<<.

Or if you want string, make a map and put desired string-equivalent there.

VP.
  • 15,509
  • 17
  • 91
  • 161