简体   繁体   中英

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. 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' .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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