考虑使用boost的异常类的以下代码:
class exception : virtual public boost::exception {
// ...
};
template<typename Exc>
class exception_impl : virtual public std::exception
, public Exc {
public:
exception_impl(const Exc& exc) : Exc(exc) {}
virtual const char* what() const throw() {return "blah";}
};
Run Code Online (Sandbox Code Playgroud)
(实际上这段代码更复杂.例如,exception_impl只有std::exception后者不是已经是直接或间接的基类Exc.但这只会分散我的问题,所以我跳过了它.)
鉴于此,我现在可以派生自己的异常类:
class some_exception : public exception {
// ...
};
Run Code Online (Sandbox Code Playgroud)
并使用它们:
struct tag_test_int;
typedef boost::error_info<tag_test_int,int> test_int_info;
void f()
{
boost::throw_exception( exception_impl<some_exception>() << test_int_info(42) );
}
Run Code Online (Sandbox Code Playgroud)
但是,事实证明,生成的异常没有该test_int_info对象.所以我更改了exception_impl构造函数以提供一些诊断信息:
exception_impl(const Exc& exc)
: …Run Code Online (Sandbox Code Playgroud)