我有什么方法可以简化以下语句? (可能是使用 boost::enable_if).

我有一个简单的班级结构 - Base 基类, Derived1, Derived2 继承 Base.

我有以下代码:

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.

我想要写的内容的一个示例(伪代码):

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_ifboost::is_base_of?

有帮助吗?

解决方案

首先,您必须选择以下选择:

  • is_base_of
  • is_convertible

两者都可以找到 <boost/type_traits.hpp>, ,后者更具允许性。

如果您只是简单地防止这种类型的实例化以进行某种组合,请使用静态断言:

// 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.

其他提示

我不想 boost::enable_if 有帮助,因为Sfinae似乎是在功能过载之间选择。

您当然可以使用模板 bool 优化选择的参数:

#include <boost/type_traits.hpp>
class Base {};

class Derived : public Base {};

template <class A, class B>
struct some_translator {};

template <typename A, typename B, bool value>
struct translator_selector;  //perhaps define type as needed

template <typename A, typename B>
struct translator_selector<A, B, true>
{
    typedef some_translator<A, B> type;
};

template <typename A, typename B>
struct translator_between
{
    typedef typename translator_selector<A, B, boost::is_base_of<Base, A>::value>::type type;
};

int main()
{
    translator_between<Base, int>::type a;
    translator_between<Derived, int>::type b;
    translator_between<float, int>::type c;  //fails
}

您可以在此处使用Anable_if和此宏来使其更可读:

#define CLASS_REQUIRES(...) typename boost::enable_if<boost::mpl::and_<__VA_ARGS__, boost::mpl::bool_<true> > >::type

那么您可以这样定义班级:

template <typename Class, typename Y, class Enable = 
CLASS_REQUIRES(boost::is_base_of<Class, Y>)> 
struct translator_between {
    typedef some_translator<Class, Y> type;
};
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top