gpt4 book ai didi

c++ - 将错误代码枚举与 std::error_code 进行比较

转载 作者:可可西里 更新时间:2023-11-01 16:05:19 24 4
gpt4 key购买 nike

我正在使用 C++11 system_error 错误代码库为我正在制作的库创建自定义错误类。我以前用 boost::error_code 做过这个,但我不能完全让它与 std::error_code 一起工作。我正在使用 GCC 4.6。

基本上,我已经布置了所有样板代码以创建错误类、error_category 和 STD 命名空间中的转换例程以将我的自定义枚举转换为 std::error_code 对象:

namespace mylib
{
namespace errc {

enum my_error
{
failed = 0
};

inline const char* error_message(int c)
{
static const char* err_msg[] =
{
"Failed",
};

assert(c < sizeof(err_msg) / sizeof(err_msg[0]));
return err_msg[c];
}

class my_error_category : public std::error_category
{
public:

my_error_category()
{ }

std::string message(int c) const
{
return error_message(c);
}

const char* name() const { return "My Error Category"; }

const static error_category& get()
{
const static my_error_category category_const;
return category_const;
}
};

} // end namespace errc
} // end namespace mylib

namespace std {

inline error_code make_error_code(mylib::errc::my_error e)
{
return error_code(static_cast<int>(e), mylib::errc::my_error_category::get());
}

template<>
struct is_error_code_enum<mylib::errc::my_error>
: std::true_type
{ };


问题是,我的错误代码枚举和 std::error_code 对象之间的隐式转换似乎不起作用,所以我不能尝试比较 的实例>std::error_code 带有枚举文字:

int main()
{
std::error_code ec1 = std::make_error_code(mylib::errc::failed); // works
std::error_code ec2 = mylib::errc::failed; // doesn't compile
bool result = (ec2 == mylib::errc::failed); // doesn't compile
}

表达式 ec2 == mylib::errc::failed 无法编译 - 我不得不说 ec2 == std::make_error_code(mylib::errc::failed)

编译器发出的错误是:

In file included from test6.cc:3:0:
/usr/include/c++/4.6/system_error: In constructor ‘std::error_code::error_code(_ErrorCodeEnum, typename std::enable_if<std::is_error_code_enum<_ErrorCodeEnum>::value>::type*) [with _ErrorCodeEnum = mylib::errc::my_error, typename std::enable_if<std::is_error_code_enum<_ErrorCodeEnum>::value>::type = void]’:
test6.cc:70:37: instantiated from here
/usr/include/c++/4.6/system_error:127:9: error: cannot convert ‘mylib::errc::my_error’ to ‘std::errc’ for argument ‘1’ to ‘std::error_code std::make_error_code(std::errc)’

这是一个 Ideone link .

那么,为什么这不起作用?我是否需要额外的样板代码来使 mylib::errc::my_error 枚举能够隐式转换为 std::error_code?我认为 std::make_error_code 的特化可以解决这个问题?

最佳答案

您必须将 error_code make_error_code(mylib::errc::my_error e) 函数从 std 移动到您的错误命名空间(mylib::errc)。请查看http://ideone.com/eSfee .

关于c++ - 将错误代码枚举与 std::error_code 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11973798/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com