当前位置: 动力学知识库 > 问答 > 编程问答 >

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

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: