我想创建一个类,它接受std :: function并允许处理指定的异常,但我不确定它是否可行.
这是一些伪草案:
//exception types
template<class... Args>
class CustomExceptionHandler
{
public:
CustomExceptionHandler(std::function<void()> clb): clb_(std::move(clb)){}
void ExecuteCallback()
{
try
{
clb_();
}
/*catch specified exception types*/
}
private:
std::function<void()> clb_;
};
//usage
CustomExceptionHandler<std::out_of_range, std::overflow_error> handler(clb);
handler.ExecuteCallback();
Run Code Online (Sandbox Code Playgroud)
我不知道如何使用可变参数模板来获取异常类型并在以后使用它.可能吗 ?
我猜那个元组可能会有所帮助.
alt*_*gel 10
这是可能的!我已经提出了一个解决方案(你可以在这里运行),它将异常类型的参数包扩展为一系列递归函数调用,其中每个函数都试图捕获一种类型的异常.然后,最里面的递归调用调用回调.
namespace detail {
template<typename First>
void catcher(std::function<void()>& clb){
try {
clb(); // invoke the callback directly
} catch (const First& e){
// TODO: handle error as needed
std::cout << "Caught an exception with type \"" << typeid(e).name();
std::cout << "\" and message \"" << e.what() << "\"\n";
}
}
template<typename First, typename Second, typename... Rest>
void catcher(std::function<void()>& clb){
try {
catcher<Second, Rest...>(clb); // invoke the callback inside of other handlers
} catch (const First& e){
// TODO: handle error as needed
std::cout << "Caught an exception with type \"" << typeid(e).name();
std::cout << "\" and message \"" << e.what() << "\"\n";
}
}
}
template<class... Args>
class CustomExceptionHandler
{
public:
CustomExceptionHandler(std::function<void()> clb): clb_(std::move(clb)){}
void ExecuteCallback()
{
detail::catcher<Args...>(clb_);
}
private:
std::function<void()> clb_;
};
int main(){
std::function<void()> clb = [](){
std::cout << "I'm gonna barf!\n";
throw std::out_of_range("Yuck");
//throw std::overflow_error("Ewww");
};
CustomExceptionHandler<std::out_of_range, std::overflow_error> handler(clb);
handler.ExecuteCallback();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
I'm gonna barf!
Caught an exception with type "St12out_of_range" and message "Yuck"
我希望有所帮助!快乐的编码
归档时间: |
|
查看次数: |
235 次 |
最近记录: |