c – 如何正确使用boost :: error_info?
发布时间:2020-12-16 05:45:43 所属栏目:百科 来源:网络整理
导读:我正在尝试跟随这个页面上的例子: 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 f
我正在尝试跟随这个页面上的例子:
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); } 解决方法#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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |