简体   繁体   English

试图使我的枚举等效于std :: error_code

[英]Trying to make my enum equivalent to std::error_code

I'm still going through std::error_code and am now trying to make my list of error enums equivalent to std::error_code. 仍在通过std :: error_code,现在尝试使我的错误枚举列表等效于std :: error_code。 I'm following what's on this tutorial but for some reason I can't make it work, I always end up with the error No viable conversion from 'my_project::my_error' to 'std::error_code' . 我正在关注教程中的内容,但由于某种原因我无法使其正常工作,我总是No viable conversion from 'my_project::my_error' to 'std::error_code'错误, No viable conversion from 'my_project::my_error' to 'std::error_code'

This is what I'm working with: 这就是我正在使用的:

#include <system_error>
#include <string>

namespace std {

  enum class my_error;

  template <>
  struct is_error_condition_enum<my_error> : public true_type {};
}

namespace my_project {
  enum class my_error {
    warning = 45836431
  };

  namespace internal {
    struct my_error_category : public std::error_category {
      const char* name() const noexcept override {
        return "AAA";
      }
      std::string message(int ev) const noexcept override {
        const std::string message = "BBB";
        return message;
      }
    };
  }
}

inline std::error_code make_error_code(const my_project::my_error &e) {
  return {static_cast<int>(e), my_project::internal::my_error_category()};
};

int main()
{
  std::error_code ec = my_project::my_error::warning;
}

This works: 这有效:

#include <system_error>
#include <string>

namespace my_project {
  enum class my_error {
    warning = 45836431
  };
}

namespace std {
  // you had a typo here, and you defined a different std::my_error class
  template <>
  struct is_error_code_enum<my_project::my_error> : public true_type {};
}

namespace my_project {

  namespace internal {
    struct my_error_category : public std::error_category {
      const char* name() const noexcept override {
        return "AAA";
      }
      std::string message(int ev) const noexcept override {
        const std::string message = "BBB";
        return message;
      }
    };
  }

inline std::error_code make_error_code(const my_project::my_error &e) {
  return {static_cast<int>(e), my_project::internal::my_error_category()};
};
}

int main()
{
  std::error_code ec = my_project::my_error::warning;
}

Clang's error messages put me on the right track because it told me why it was not using the right constructor. Clang的错误消息使我走上正轨,因为它告诉我为什么它没有使用正确的构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM