Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use boost::error_info correctly?

I'm trying to following the examples on this page:

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

The minute I try the following line:

throw file_read_error() << errno_code(errno);

I get an error:

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

How do I get this to work??

Ideally I want to create something like this:

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

But I can't even get the first examples to work.

Edit: Here is a brief example of what generates error C2440 for me:

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);
}
like image 626
Mark Ingram Avatar asked Sep 23 '10 20:09

Mark Ingram


3 Answers

#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;
        }
    }
}

produces

samm@macmini> ./a.out 
some error
my extra info
like image 128
Sam Miller Avatar answered Nov 14 '22 17:11

Sam Miller


Sam Miller gave me a clue as to what the problem was. I just needed to include:

#include <boost/exception/all.hpp>

Thanks for your answers.

like image 9
Mark Ingram Avatar answered Nov 14 '22 17:11

Mark Ingram


try:

#include <boost/exception/error_info.hpp>
#include <errno.h>

throw file_read_error() << boost::errinfo_errno(errno);

even better:

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

Your HRESULTErrorInfo example seems correct.

like image 2
ronag Avatar answered Nov 14 '22 16:11

ronag