代码之家  ›  专栏  ›  技术社区  ›  Mark Ingram

如何正确使用boost::error\u info?

  •  10
  • Mark Ingram  · 技术社区  · 14 年前

    http://www.boost.org/doc/libs/1_40_0/libs/exception/doc/motivation.html

    当我尝试下面这句话的时候:

    throw file_read_error() << errno_code(errno);
    

    我得到一个错误:

    error C2440: '<function-style-cast>' : cannot convert from 'int' to 'errno_code'
    

    我怎么才能让它工作??

    理想情况下,我想创造这样的东西:

    typedef boost::error_info<struct tag_HRESULTErrorInfo, HRESULT> HRESULTErrorInfo;
    

    但我连第一个例子都做不到。

    编辑:下面是一个为我生成错误C2440的简单示例:

    struct exception_base: virtual std::exception, virtual boost::exception { };
    struct io_error: virtual exception_base { };
    struct file_read_error: virtual io_error { };
    
    typedef boost::error_info<struct tag_errno_code,int> errno_code;
    
    void foo()
    {
        // error C2440: '<function-style-cast>' : cannot convert from 'int' to 'errno_code'
        throw file_read_error() << errno_code(errno);
    }
    
    3 回复  |  直到 14 年前
        1
  •  16
  •   Sam Miller    14 年前
    #include <boost/exception/all.hpp>
    
    #include <boost/throw_exception.hpp>
    
    #include <iostream>
    #include <stdexcept>
    #include <string>
    
    typedef boost::error_info<struct my_tag,std::string> my_tag_error_info;
    
    int
    main()
    {
        try {
            boost::throw_exception(
                    boost::enable_error_info( std::runtime_error( "some error" ) ) 
                    << my_tag_error_info("my extra info")
                    );
        } catch ( const std::exception& e ) {
            std::cerr << e.what() << std::endl;
            if ( std::string const * extra  = boost::get_error_info<my_tag_error_info>(e) ) {
                std::cout << *extra << std::endl;
            }
        }
    }
    

    生产

    samm@macmini> ./a.out 
    some error
    my extra info
    
        2
  •  8
  •   Community CDub    8 年前

    Sam Miller 给了我一个问题的线索。我只需要包括:

    #include <boost/exception/all.hpp>

    谢谢你的回答。

        3
  •  2
  •   ronag    14 年前

    尝试:

    #include <boost/exception/error_info.hpp>
    #include <errno.h>
    
    throw file_read_error() << boost::errinfo_errno(errno);
    

    BOOST_THROW_EXCEPTION(file_read_error() << errinfo_errno(errno));
    

    您的HRESULTErrorInfo示例似乎是正确的。