mercredi 24 juin 2015

calling enum << operator for string composition

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();

Aucun commentaire:

Enregistrer un commentaire