C ++ boost enable_if问题 [英] C++ boost enable_if question
问题描述
我有办法简化以下语句吗? (可能使用 boost :: enable_if
)
Do I have any way to simplify the following statements? (probably, using boost::enable_if
).
结构 - 基本
基类, Derived1
, Derived2
基本
。
I have a simple class structure - Base
base class, Derived1
, Derived2
inherit from Base
.
我有以下代码:
I have the following code:
template <typename Y> struct translator_between<Base, Y> {
typedef some_translator<Base, Y> type;
};
template <typename Y> struct translator_between<Derived1, Y> {
typedef some_translator<Derived1, Y> type;
};
template <typename Y> struct translator_between<Derived2, Y> {
typedef some_translator<Derived2, Y> type;
};
我想使用 translator_between code>。
I want to write the same statement using one template specialization of translator_between
.
template <typename Class, typename Y>
ONLY_INSTANTIATE_THIS_TEMPLATE_IF (Class is 'Base' or any derived from 'Base')
struct translator_between<Class, Y> {
typedef some_translator<Class, Y> type;
};
任何方式使用 boost :: enable_if
和 boost :: is_base_of
?
推荐答案
必须选择以下选项:
-
is_base_of
-
is_convertible
is_base_of
is_convertible
$ c>< boost / type_traits.hpp> ,后者更为宽容。
both can be found in <boost/type_traits.hpp>
, the latter being more permissive.
如果你简单地阻止这个实例化键入一些组合,然后使用静态断言:
If you with to simply prevent the instantiation of this type for some combination, then use a static assert:
// C++03
#include <boost/mpl/assert.hpp>
template <typename From, typename To>
struct translator_between
{
BOOST_MPL_ASSERT((boost::is_base_of<To,From>));
typedef translator_selector<From,To> type;
};
// C++0x
template <typename From, typename To>
struct translator_between
{
static_assert(boost::is_base_of<To,From>::value,
"From does not derive from To");
typedef translator_selector<From,To> type;
};
由于此处没有重载解析,因此您不需要 enable_if
。
Since there is no overload resolution taking place here, you don't need enable_if
.
这篇关于C ++ boost enable_if问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!