c + +提振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
.
的我有以下的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):的
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
?
推荐答案
首先,你得挑中你的选择:
First, you'll have to pick your choice among:
-
is_base_of
-
is_convertible
is_base_of
is_convertible
都可以发现&LT;升压/ type_traits.hpp方式&gt;
,后者是更宽容的
both can be found in <boost/type_traits.hpp>
, the latter being more permissive.
如果您简单地prevent这种类型的某种组合的实例,然后使用一个静态断言:
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
。
这篇关于c + +提振enable_if问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!