如何在运行时确定Exception_ptr指向的异常类型?

jot*_*tik 5 c++ exception typeinfo c++11

在 C++11 及更高版本中,exception_ptr 可以使用 检索当前异常current_exception()。是否可以在运行时确定所指向的异常的类型?

更准确地说,如何获取type_infoan 指向的异常的 a引用exception_ptr?我知道可以catch基于类型,但是程序员需要catch为所有可能的异常类型编写块,这不是这个问题的解决方案。

try {
    userProvidedRuntimePlugin.executeAction(); // May throw anything
} catch (...) {
    auto e = std::current_exception();
    std::type_info & info = /* ??? */;
    std::cerr << "Exception of type " << info.name() << " thrown." << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

Les*_*icz 6

尝试如下操作:

#include <cxxabi.h>

using namespace __cxxabiv1;

std::string util_demangle(std::string to_demangle)
{
    int status = 0;
    char * buff = __cxxabiv1::__cxa_demangle(to_demangle.c_str(), NULL, NULL, &status);
    if (!buff) return to_demangle;
    std::string demangled = buff;
    std::free(buff);
    return demangled;
}

try
{
   /* .... */
}
catch(...)
{
   std::cout <<"exception type: '" << util_demangle(abi::__cxa_current_exception_type()->name()) << "'\n";
}
Run Code Online (Sandbox Code Playgroud)