提升::enable_if有两个条件

boost::enable_if with two conditions

本文关键字:条件 两个 enable if 提升      更新时间:2023-10-16

正如你在下面的示例中看到的,我目前使用boost::enable_if作为分配函数的返回值。目标是避免抽象类型的编译错误:

template <typename T>
typename boost::enable_if<boost::is_abstract<T>,T*>::type no_abstract_new()
{
assert(false);
return 0;
}
template <typename T>
typename boost::disable_if<boost::is_abstract<T>,T*>::type no_abstract_new()
{
return new T;
}

现在,我还想排除从自己的名为has_no_default_constructor的类继承的类。有没有办法在boost::enable_if的情况下or像这样不正确的代码:

template <typename T>
typename boost::enable_if<boost::is_abstract<T>
|| boost::is_base_of<has_no_default_constructor,T>,T*>::type default_constructor_new()
{
assert(false);
return 0;
}
template <typename T>
typename boost::disable_if<boost::is_abstract<T>
|| boost::is_base_of<has_no_default_constructor,T>,T*>::type default_constructor_new()
{
return new T;
}

还是我必须实现自己的特质类来完成这项工作?(我对此完全迷茫了。我理解这个想法,但我觉得自己可以做(

笔记:

  • 出于兼容性原因,我不使用 C++11
  • 我知道has_default_constructor存在于 C++11 中,但不是在 C++11 之前
  • boost::has_default_constructor存在,但如果编译时没有 C++11,则只是boost::has_trivial_constructor的别名

还有

template <bool B, class T = void> struct enable_if_c;

请注意,它采用bool作为第一个参数而不是类型。因此,以下内容应该没问题

template <typename T>
typename boost::enable_if_c<boost::is_abstract<T>::value
|| boost::is_base_of<has_no_default_constructor,T>::value
,T*>::type default_constructor_new()
{
assert(false);
return 0;
}

对于其他重载也是如此。