rethrow_if_nested可能的实现

rethrow_if_nested possible implementation

本文关键字:实现 nested if rethrow      更新时间:2023-10-16

cppreference.com 提供了有关rethrow_if_nested可能实现的一些详细信息。这些细节是我感兴趣的。虽然大多数表达对我来说似乎是合理的,但can_dynamic_cast的定义有点令人困惑:

template <class E>
struct can_dynamic_cast
: std::integral_constant<bool,
std::is_polymorphic<E>::value &&
(!std::is_base_of<std::nested_exception, E>::value ||
std::is_convertible<E*, std::nested_exception*>::value)
> { };

我无法想象在编译时(!std::is_base_of<std::nested_exception, E>::value || std::is_convertible<E*, std::nested_exception*>::value)计算结果变成false的情况。更具体地说,

  • 如果std::is_base_of<std::nested_exception, E>::value == false,则!std::is_base_of<std::nested_exception, E>::value == true
  • 如果std::is_base_of<std::nested_exception, E>::value == true,则 类型E派生自std::nested_exception,无论如何我们都可以E*转换为std::nested_exception*

所以,问题是我的讨论有什么问题,为什么can_dynamic_cast要以这种方式实施?

注意:据我所知,GCC 7实现了上述逻辑。同时,LLVM的实现似乎检查了参数的类型是否是多态的,没有别的:

template <class _Ep>                                                            
inline _LIBCPP_INLINE_VISIBILITY                                                
void                                                                            
rethrow_if_nested(const _Ep& __e, typename enable_if<                           
is_polymorphic<_Ep>::value                   
>::type* = 0)

std::nested_exceptionE的模糊或无法访问的基础时(例如E私自继承自std::nested_exception(,std::is_base_of<std::nested_exception, E>::value是正确的,但E*不能转换为std::nested_exception*