c – 如何正确使用boost :: error_info?

前端之家收集整理的这篇文章主要介绍了c – 如何正确使用boost :: error_info?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试跟随这个页面上的例子:

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

一分钟我尝试以下行:

  1. throw file_read_error() << errno_code(errno);

我收到一个错误

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

我该如何让这个工作?

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

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

但我甚至不能得到第一个例子来工作.

编辑:这是一个简短的例子,为我生成错误C2440:

  1. struct exception_base: virtual std::exception,virtual boost::exception { };
  2. struct io_error: virtual exception_base { };
  3. struct file_read_error: virtual io_error { };
  4.  
  5. typedef boost::error_info<struct tag_errno_code,int> errno_code;
  6.  
  7. void foo()
  8. {
  9. // error C2440: '<function-style-cast>' : cannot convert from 'int' to 'errno_code'
  10. throw file_read_error() << errno_code(errno);
  11. }

解决方法

  1. #include <boost/exception/all.hpp>
  2.  
  3. #include <boost/throw_exception.hpp>
  4.  
  5. #include <iostream>
  6. #include <stdexcept>
  7. #include <string>
  8.  
  9. typedef boost::error_info<struct my_tag,std::string> my_tag_error_info;
  10.  
  11. int
  12. main()
  13. {
  14. try {
  15. boost::throw_exception(
  16. boost::enable_error_info( std::runtime_error( "some error" ) )
  17. << my_tag_error_info("my extra info")
  18. );
  19. } catch ( const std::exception& e ) {
  20. std::cerr << e.what() << std::endl;
  21. if ( std::string const * extra = boost::get_error_info<my_tag_error_info>(e) ) {
  22. std::cout << *extra << std::endl;
  23. }
  24. }
  25. }

产生

  1. samm@macmini> ./a.out
  2. some error
  3. my extra info

猜你在找的C&C++相关文章