首页 > 解决方案 > boost::enable_if 有两个条件

问题描述

正如您在以下示例中看到的,我目前使用 aboost::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. 有没有办法让 aor处于 的状态boost::enable_if像这样不正确的代码:

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++boosttypetraitsc++03

解决方案


还有

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;
}

和其他重载类似。


推荐阅读