Is it possible to convert a boost::system::error_code to a std:error_code?

后端 未结 3 371
感情败类
感情败类 2021-01-31 10:31

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, therefor

3条回答
  •  抹茶落季
    2021-01-31 11:06

    I adapted the above solution into a shorter solution. Using a thread_local std::map to map between the category name to its instance so no locking is needed.

    The limitation is that you can't pass error codes between threads since the category pointer will be different.(Converting it to a locking function is simple enough if you don't want to use the thread_local storage)

    Also I feed it is more compact.

    #include 
    #include 
    #include 
    
    namespace std
    {
    
    error_code make_error_code(boost::system::error_code error)
    {
        struct CategoryAdapter : public error_category
        {
            CategoryAdapter(const boost::system::error_category& category)
                : m_category(category)
            {
            }
    
            const char* name() const noexcept
            {
                return m_category.name();
            }
    
            std::string message(int ev) const
            {
                return m_category.message(ev);
            }
    
        private:
            const boost::system::error_category& m_category;
        };
    
        static thread_local map nameToCategory;
        auto result = nameToCategory.emplace(error.category().name(), error.category());
        auto& category = result.first->second;
        return error_code(error.value(), category);
    }
    
    };
    
    int main() {
        auto a = boost::system::errc::make_error_code(boost::system::errc::address_family_not_supported);
        auto b = std::make_error_code(a);
        std::cout << b.message() << std::endl;
    }
    

提交回复
热议问题