为字符串组合调用枚举 << 运算符
calling enum << operator for string composition
假设我们有枚举并实现了 operator<<
将枚举值转换为字符串。是否可以在字符串构造或类似的过程中调用此运算符?我当前的方法使用 std::stringstream
在枚举上调用 << 并从 std::stringstream
中提取字符串。还有别的办法吗?使用 std::cout <<
不是一个选项。
示例代码:
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";
}
用法:
Status s = Status::OK;
std::stringstream stream;
stream << s;
std::string statusString = s.str().c_str();
很遗憾,这里没有您想要的任何优雅的解决方案。
如果可以的话,我们可能会使用用户定义的转换,但它需要是一个非静态成员函数,这在 enums
中是不可能的。
但是您可以像使用 operator<<
.
一样始终使用依赖于参数的查找
或者,如果您需要字符串,请制作一个映射并将所需的字符串等价物放在那里。
假设我们有枚举并实现了 operator<<
将枚举值转换为字符串。是否可以在字符串构造或类似的过程中调用此运算符?我当前的方法使用 std::stringstream
在枚举上调用 << 并从 std::stringstream
中提取字符串。还有别的办法吗?使用 std::cout <<
不是一个选项。
示例代码:
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";
}
用法:
Status s = Status::OK;
std::stringstream stream;
stream << s;
std::string statusString = s.str().c_str();
很遗憾,这里没有您想要的任何优雅的解决方案。
如果可以的话,我们可能会使用用户定义的转换,但它需要是一个非静态成员函数,这在 enums
中是不可能的。
但是您可以像使用 operator<<
.
或者,如果您需要字符串,请制作一个映射并将所需的字符串等价物放在那里。