如何正确使用boost :: error_info?

Mar*_*ram 11 c++ error-handling boost exception-handling visual-studio-2008

我正在尝试按照此页面上的示例进行操作:

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

我尝试以下一行的那一刻:

throw file_read_error() << errno_code(errno);
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

error C2440: '<function-style-cast>' : cannot convert from 'int' to 'errno_code'
Run Code Online (Sandbox Code Playgroud)

我如何让它工作?

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

typedef boost::error_info<struct tag_HRESULTErrorInfo, HRESULT> HRESULTErrorInfo;
Run Code Online (Sandbox Code Playgroud)

但我甚至无法得到第一个可行的例子.

编辑:以下是为我生成错误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);
}
Run Code Online (Sandbox Code Playgroud)

Sam*_*ler 16

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

产生

samm@macmini> ./a.out 
some error
my extra info
Run Code Online (Sandbox Code Playgroud)


Mar*_*ram 8

山姆米勒给了我一个线索,问题是什么.我只需要包括:

#include <boost/exception/all.hpp>

谢谢你的回答.

  • 为什么地狱有正确的答案被贬低?#include修复了我上面发布的代码. (7认同)