【发布时间】: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<std::disjunction<boost::is_abstract<T>, boost::is_base_of<has_no_default_constructor,T>>, T*>::type。在 Boost 中,boost::hana::or_ 似乎完成了这项工作。 -
您是否有机会升级,至少是库的一部分?在这种情况下,请确保尽可能接近地模仿修订后的标准库,以便您以后可以删除自己的代码。您可能应该将其放入自己的标头和命名空间中,这样您就可以更轻松地继续前进。
标签: c++ boost typetraits c++03