我想创建一个接受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();我不知道如何使用各种模板来获取异常类型,然后再使用它。有可能吗?
我想元组可能会有帮助。
发布于 2019-02-21 21:18:37
这是可能的!我提出了一个解决方案(您可以运行这里),它将异常类型的参数包扩展为一系列递归函数调用,每个函数都试图捕获一种类型的异常。然后,最内部的递归调用调用回调。
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;
}输出:
I'm gonna barf!Caught an exception with type "St12out_of_range" and message "Yuck"
发布于 2019-02-21 21:42:21
template<typename E0, typename ... En>
class ExceptionCatcher
{
public:
template<typename F>
void doit(F&& f)
{
try
{
ExceptionCatcher<En...> catcher;
catcher.doit(std::forward<F>(f));
}
catch(const E0 &)
{
std::cout << __PRETTY_FUNCTION__ << '\n';
}
}
};
template<typename E0>
class ExceptionCatcher<E0>
{
public:
template<typename F>
void doit(F&& f)
{
try
{
f();
}
catch(const E0 &)
{
std::cout << __PRETTY_FUNCTION__ << '\n';
}
}
};https://stackoverflow.com/questions/54815963
复制相似问题