c++ - 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++11
- 我知道
has_default_constructor
存在于 C++11 中,但不是在 C++11 之前 boost::has_default_constructor
存在,但只是在boost::has_trivial_constructor
没有 C++11 的情况下编译的别名
解决方案
还有
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;
}
和其他重载类似。