c++ 将枚举值转换为字符串

mmvthczy  于 2023-11-19  发布在  其他
关注(0)|答案(3)|浏览(218)

我有以下代码片段:

  1. enum class Code : uint8_t
  2. {
  3. A = 0,
  4. B = 1,
  5. C = 2
  6. }

字符串
如何在枚举中添加一个转换操作符(如果可能的话,也可以添加类似的操作符),这样当我将枚举对象传递给接受std::string的函数时,对象将被隐式转换为std::string。目标是将0转换为字符串"0",将1转换为"1"等。
注意:我不想添加像toString这样的函数,因为我需要隐式转换

jk9hmnmh

jk9hmnmh1#

我最初发布了一个如何使用一些隐式转换技巧实现这一点的例子,但意识到这可以进一步简化。
我假设你写了你想传递Code类型的方法;最简单的选择是添加一个简单的重载,它也接受Code,执行转换为std::string,然后将结果传递给另一个方法,例如。

  1. void work(std::string);
  2. /* adding.... */
  3. void work(Code c)
  4. {
  5. switch (c)
  6. {
  7. case Code::A: return work("A");
  8. case Code::B: return work("B");
  9. case Code::C: return work("C");
  10. default: __builtin_unreachable();
  11. }
  12. }

字符串
如果该方法是标准库的一部分,我相信在这里添加您自己的重载将是UB,但是您可以在新的名称空间中引入它,并使用ADL来解决其余问题。
最好的答案最终取决于你所处的确切情况,但这可能是一个很好的起点。

展开查看全部
gr8qqesn

gr8qqesn2#

我不知道你为什么需要这个,所以我的建议可能有点离谱。但是如果你需要一个可以被视为Code或字符串的值,那么我们可以创建一个 Package 器类,它将转换为以下任何一种:

  1. struct Code_class
  2. {
  3. Code c;
  4. Code_class(Code c) : c{c} {}
  5. operator Code() const
  6. {
  7. return c;
  8. }
  9. #define X(x) case Code::x: return #x
  10. operator std::string() const
  11. {
  12. switch (c) {
  13. X(A);
  14. X(B);
  15. X(C);
  16. }
  17. std::unreachable();
  18. }
  19. #undef X
  20. };

字符串

完整demo

  1. #include <cstdint>
  2. #include <string>
  3. #include <utility>
  4. enum class Code : uint8_t
  5. {
  6. A = 0,
  7. B = 1,
  8. C = 2
  9. };
  10. struct Code_class
  11. {
  12. Code c;
  13. /* implicit */ Code_class(Code c) : c{c} {}
  14. operator Code() const
  15. {
  16. return c;
  17. }
  18. #define X(x) case Code::x: return #x
  19. operator std::string() const
  20. {
  21. switch (c) {
  22. X(A);
  23. X(B);
  24. X(C);
  25. }
  26. std::unreachable();
  27. }
  28. #undef X
  29. };
  30. #include <iostream>
  31. int main()
  32. {
  33. auto m = Code::A;
  34. Code_class p = m;
  35. const std::string s = p;
  36. std::cout << s << '\n';
  37. }

展开查看全部
cgfeq70w

cgfeq70w3#

char是一种整数,所以我们可以声明char的枚举。

  1. #include <iostream>
  2. enum struct Cnum : char { h = 'h', o = 'o', e = 'e', l = 'l' , num_0 = '0' };
  3. std::ostream& operator<<(std::ostream& os, Cnum c) {
  4. os << static_cast<char>(c);
  5. return os;
  6. }
  7. int main() {
  8. std::cout << Cnum::h << Cnum::e << Cnum::l << Cnum::l << Cnum::o << Cnum::num_0 << "\n";//print hello0
  9. }

字符串
然后你可以在以后从char中构建string。

展开查看全部

相关问题