是否可以将 boost::system::error_code 转换为 std:error_code?
我想尽可能地用标准 C++ 中的等价物替换外部库(如 boost),如果它们存在并且有可能,以尽量减少依赖性,因此我想知道是否存在转换 boost 的安全方法::system::error_code
到 std::error_code
.伪代码示例:
I want to replace external libraries (like boost) as much as possible with their equivalents in standard C++ if they exist and it is possible, to minimize dependencies, therefore I wonder if there exists a safe way to convert boost::system::error_code
to std::error_code
. Pseudo code example:
void func(const std::error_code & err)
{
if(err) {
//error
} else {
//success
}
}
boost::system::error_code boost_err = foo(); //foo() returns a boost::system::error_code
std::error_code std_err = magic_code_here; //convert boost_err to std::error_code here
func(std_err);
最重要的不是完全相同的错误,而是尽可能接近最后是否是错误.有什么聪明的解决方案吗?
The most important it is not the exactly the same error, just so close to as possible and at last if is an error or not. Are there any smart solutions?
提前致谢!
推荐答案
自 C++-11 (std::errc) 起,boost/system/error_code.hpp 将相同的错误代码映射到 std::errc,在系统头文件system_error
中定义.
Since C++-11 (std::errc), boost/system/error_code.hpp maps the same error codes to std::errc, which is defined in the system header system_error
.
您可以比较两个枚举,它们在功能上应该是等效的,因为它们似乎都基于 POSIX 标准.可能需要演员阵容.
You can compare both enums and they should be functionally equivalent because they both appear to be based on the POSIX standard. May require a cast.
例如
namespace posix_error
{
enum posix_errno
{
success = 0,
address_family_not_supported = EAFNOSUPPORT,
address_in_use = EADDRINUSE,
address_not_available = EADDRNOTAVAIL,
already_connected = EISCONN,
argument_list_too_long = E2BIG,
argument_out_of_domain = EDOM,
bad_address = EFAULT,
bad_file_descriptor = EBADF,
bad_message = EBADMSG,
....
}
}
和 std::errc
address_family_not_supported error condition corresponding to POSIX code EAFNOSUPPORT
address_in_use error condition corresponding to POSIX code EADDRINUSE
address_not_available error condition corresponding to POSIX code EADDRNOTAVAIL
already_connected error condition corresponding to POSIX code EISCONN
argument_list_too_long error condition corresponding to POSIX code E2BIG
argument_out_of_domain error condition corresponding to POSIX code EDOM
bad_address error condition corresponding to POSIX code EFAULT
相关文章