【问题标题】:boost::enable_if with two conditionsboost::enable_if 有两个条件
【发布时间】:2018-10-01 13:24:03
【问题描述】:

正如您在以下示例中看到的,我目前使用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 的别名

【问题讨论】:

  • 有什么错误?
  • @user463035818 :你是对的。看起来,它适用于boost::enable_if_c。谢谢。 :-)
  • 使用类型,它将是typename boost::enable_if&lt;std::disjunction&lt;boost::is_abstract&lt;T&gt;, boost::is_base_of&lt;has_no_default_constructor,T&gt;&gt;, T*&gt;::type。在 Boost 中,boost::hana::or_ 似乎完成了这项工作。
  • 您是否有机会升级,至少是库的一部分?在这种情况下,请确保尽可能接近地模仿修订后的标准库,以便您以后可以删除自己的代码。您可能应该将其放入自己的标头和命名空间中,这样您就可以更轻松地继续前进。

标签: c++ boost typetraits c++03


【解决方案1】:

还有

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

其他重载也类似。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多