c++booststderror-code

Is it possible to convert a boost::system::error_code to a 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?

Thanks in advance!


Solution

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

    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.

    For example,

    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,
            ....
           }
         }
    

    and 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