我正在尝试跟随这个页面上的例子:
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;
但我甚至不能得到第一个例子来工作.
- 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);
- }
解决方法
- #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