【问题标题】:How to use boost::error_info correctly?如何正确使用 boost::error_info?
【发布时间】:2011-04-16 11:31:35
【问题描述】:

我正在尝试遵循此页面上的示例:

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

【问题讨论】:

  • 您能否发布一个在遇到 C2440 错误时尝试编译的完整最小示例?
  • 查看链接上的示例。我无法让throw file_open_error() &lt;&lt; errno_code(errno); 工作。
  • 对于遇到这种情况的其他人:Boost Exception 文档中的“动机”页面不完整——这里有一个更好的例子:boost.org/doc/libs/1_56_0/libs/exception/doc/…,他们列出了正确的标题。

标签: c++ visual-studio-2008 boost exception-handling error-handling


【解决方案1】:
#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

【讨论】:

    【解决方案2】:

    尝试:

    #include <boost/exception/error_info.hpp>
    #include <errno.h>
    
    throw file_read_error() << boost::errinfo_errno(errno);
    

    更好:

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

    您的 HRESULTErrorInfo 示例似乎正确。

    【讨论】:

    • 感谢您的示例,我在 BOOST_THROW_EXCEPTION() 之外有
    【解决方案3】:

    Sam Miller 给了我一个关于问题所在的线索。我只需要包括:

    #include &lt;boost/exception/all.hpp&gt;

    感谢您的回答。

    【讨论】:

    • 为什么正确答案被否决了? #include 修复了我在上面发布的代码。
    • 模板相关错误的示例,编译器错误消息与问题的原因完全无关。谢谢你。
    猜你喜欢
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多