是否可以将boost :: system :: error_code转换为std:error_code?

Fre*_*rik 17 c++ boost std error-code

我想尽可能地用标准C++中的等价物替换外部库(如boost),如果它们存在且可能,最小化依赖性,因此我想知道是否存在转换boost::system::error_code为安全的方法std::error_code.伪代码示例:

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);
Run Code Online (Sandbox Code Playgroud)

最重要的不是完全相同的错误,只是尽可能接近,最后如果是错误.有智能解决方案吗?

提前致谢!

Scr*_*dib 10

我有这个完全相同的问题,因为我想使用,std::error_code但也使用其他使用的boost库boost::system::error_code(例如boost ASIO).接受的答案适用于处理的错误代码std::generic_category(),因为它们是来自boost的通用错误代码的简单转换,但它不适用于您也想要处理自定义错误类别的一般情况.

所以,我创建了下面的代码作为一种通用的boost::system::error_code-到- std::error_code转换器.它的工作原理是std::error_category为每个动态创建一个垫片boost::system::error_category,将调用转发到底层的Boost错误类别.由于错误类别需要是单例(或至少像单例一样),我不希望存在大量的内存爆炸.

我也只是将boost::system::generic_category()对象转换为使用,std::generic_category()因为它们的行为应该相同.我曾经想要做同样的事情system_category(),但是在测试VC++ 10时它打印出错误的消息(我认为它应该打印出你得到的东西FormatMessage,但似乎使用strerror,Boost FormatMessage按预期使用).

要使用它,只需调用BoostToErrorCode(),定义如下.

只是一个警告,我今天刚刚写了这个,所以它只进行了基本的测试.您可以按照自己喜欢的方式使用它,但这样做需要您自担风险.

//==================================================================================================
// These classes implement a shim for converting a boost::system::error_code to a std::error_code.
// Unfortunately this isn't straightforward since it the error_code classes use a number of
// incompatible singletons.
//
// To accomplish this we dynamically create a shim for every boost error category that passes
// the std::error_category calls on to the appropriate boost::system::error_category calls.
//==================================================================================================
#include <boost/system/error_code.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/once.hpp>
#include <boost/thread/locks.hpp>

#include <system_error>
namespace
{
    // This class passes the std::error_category functions through to the
    // boost::system::error_category object.
    class BoostErrorCategoryShim : public std::error_category
    {
    public:
        BoostErrorCategoryShim( const boost::system::error_category& in_boostErrorCategory )
            :m_boostErrorCategory(in_boostErrorCategory), m_name(std::string("boost.") + in_boostErrorCategory.name()) {}

        virtual const char *name() const;
        virtual std::string message(value_type in_errorValue) const;
        virtual std::error_condition default_error_condition(value_type in_errorValue) const;

    private:
        // The target boost error category.
        const boost::system::error_category& m_boostErrorCategory;

        // The modified name of the error category.
        const std::string m_name;
    };

    // A converter class that maintains a mapping between a boost::system::error_category and a
    // std::error_category.
    class BoostErrorCodeConverter
    {
    public:
        const std::error_category& GetErrorCategory( const boost::system::error_category& in_boostErrorCategory )
        {
            boost::lock_guard<boost::mutex> lock(m_mutex);

            // Check if we already have an entry for this error category, if so we return it directly.
            ConversionMapType::iterator stdErrorCategoryIt = m_conversionMap.find(&in_boostErrorCategory);
            if( stdErrorCategoryIt != m_conversionMap.end() )
                return *stdErrorCategoryIt->second;

            // We don't have an entry for this error category, create one and add it to the map.                
            const std::pair<ConversionMapType::iterator, bool> insertResult = m_conversionMap.insert(
                ConversionMapType::value_type(
                    &in_boostErrorCategory, 
                    std::unique_ptr<const BoostErrorCategoryShim>(new BoostErrorCategoryShim(in_boostErrorCategory))) );

            // Return the newly created category.
            return *insertResult.first->second;
        }

    private:
        // We keep a mapping of boost::system::error_category to our error category shims.  The
        // error categories are implemented as singletons so there should be relatively few of
        // these.
        typedef std::unordered_map<const boost::system::error_category*, std::unique_ptr<const BoostErrorCategoryShim>> ConversionMapType;
        ConversionMapType m_conversionMap;

        // This is accessed globally so we must manage access.
        boost::mutex m_mutex;
    };


    namespace Private
    {
        // The init flag.
        boost::once_flag g_onceFlag = BOOST_ONCE_INIT;

        // The pointer to the converter, set in CreateOnce.
        BoostErrorCodeConverter* g_converter = nullptr;

        // Create the log target manager.
        void CreateBoostErrorCodeConverterOnce()
        {
            static BoostErrorCodeConverter converter;
            g_converter = &converter;
        }
    }

    // Get the log target manager.
    BoostErrorCodeConverter& GetBoostErrorCodeConverter()
    {
        boost::call_once( Private::g_onceFlag, &Private::CreateBoostErrorCodeConverterOnce );

        return *Private::g_converter;
    }

    const std::error_category& GetConvertedErrorCategory( const boost::system::error_category& in_errorCategory )
    {
        // If we're accessing boost::system::generic_category() or boost::system::system_category()
        // then just convert to the std::error_code versions.
        if( in_errorCategory == boost::system::generic_category() )
            return std::generic_category();

        // I thought this should work, but at least in VC++10 std::error_category interprets the
        // errors as generic instead of system errors.  This means an error returned by
        // GetLastError() like 5 (access denied) gets interpreted incorrectly as IO error.
        //if( in_errorCategory == boost::system::system_category() )
        //  return std::system_category();

        // The error_category was not one of the standard boost error categories, use a converter.
        return GetBoostErrorCodeConverter().GetErrorCategory(in_errorCategory);
    }


    // BoostErrorCategoryShim implementation.
    const char* BoostErrorCategoryShim::name() const
    {
        return m_name.c_str();
    }

    std::string BoostErrorCategoryShim::message(value_type in_errorValue) const
    {
        return m_boostErrorCategory.message(in_errorValue);
    }

    std::error_condition BoostErrorCategoryShim::default_error_condition(value_type in_errorValue) const
    {
        const boost::system::error_condition boostErrorCondition = m_boostErrorCategory.default_error_condition(in_errorValue);

        // We have to convert the error category here since it may not have the same category as
        // in_errorValue.
        return std::error_condition( boostErrorCondition.value(), GetConvertedErrorCategory(boostErrorCondition.category()) );
    }
}

std::error_code BoostToErrorCode( boost::system::error_code in_errorCode )
{
    return std::error_code( in_errorCode.value(), GetConvertedErrorCategory(in_errorCode.category()) );
}
Run Code Online (Sandbox Code Playgroud)

  • @sehe AFAIK它仍在使用中。我可以看到它是对 boost 的一个有用的补充,因为从概念上讲,错误代码的 boost 和 std 版本执行完全相同的操作,只是由于类型系统而不兼容。在这种情况下,最好直接在 boost 错误类别类中实现。这将消除对互斥锁和映射的需要,并使转换成为 noexcept,但代价是每个类别多一些字节。或者也许它可以直接从 std 派生,因为您可能还希望能够从 std-&gt;boost 进行转换? (2认同)

小智 9

从C++ - 11(std :: errc)开始,boost/system/error_code.hpp将相同的错误代码映射到std :: errc,后者在系统头中定义system_error.

您可以比较两个枚举,它们应该在功能上等效,因为它们似乎都基于POSIX标准.可能需要演员.

例如,

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,
        ....
       }
     }
Run Code Online (Sandbox Code Playgroud)

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 
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,我通过使用以下代码使其工作:std :: make_error_code(static_cast <std :: errc :: errc>(err.value())) - 其中err是boost :: system的实例/引用: :错误代码. (4认同)