22

外部ライブラリ (boost など) が存在する場合は、標準 C++ の同等のものに可能な限り置き換えて、依存関係を最小限に抑えたいと考えてい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);

最も重要なのは、まったく同じエラーではないことです。可能な限り近いものであり、最後にエラーかどうかです。スマートなソリューションはありますか?

前もって感謝します!

4

3 に答える 3

12

使用したかったので、まったく同じ質問std::error_codeがありましたが、使用する他のブーストライブラリboost::system::error_code(ブーストASIOなど)も使用していました。承認された回答はstd::generic_category()、ブーストの一般的なエラー コードからの単純なキャストであるため、によって処理されるエラー コードに対して機能しますが、カスタム エラー カテゴリも処理する一般的なケースでは機能しません。

そこで、汎用boost::system::error_codeのコンバーターとして次のコードを作成しましたstd::error_codestd::error_categoryこれは、各 の shim を動的に作成しboost::system::error_category、呼び出しを基になる Boost エラー カテゴリに転送することによって機能します。エラー カテゴリはシングルトン (または少なくともこの場合のようにシングルトンに似ている) である必要があるため、メモリの爆発が大きくなるとは考えていません。

また、オブジェクトは同じように動作するはずなので、boost::system::generic_category()オブジェクトを使用するように変換するだけです。std::generic_category()についても同じことをしたかったのですが、system_category()VC++10 でのテストでは間違ったメッセージが出力されました ( から取得したものを出力する必要があると思いますがFormatMessagestrerrorBoost は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()) );
}
于 2012-05-12T00:08:29.383 に答える
9

C++-11 (std::errc) 以降、boost/system/error_code.hppは同じエラー コードをシステム ヘッダーで定義されているstd::errcsystem_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,
        ....
       }
     }

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 
于 2012-04-16T16:20:21.663 に答える