3

我有什么方法可以简化以下陈述吗?(可能,使用boost::enable_if

我有一个简单的类结构 -Base基类Derived1Derived2继承自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_if有什么方法可以使用and来实现这一点boost::is_base_of

4

3 回答 3

4

我认为没有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
}
于 2010-09-26T18:01:08.930 回答
4

首先,您必须在以下选项中做出选择:

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

于 2010-09-27T07:23:59.823 回答
0

您可以在此处使用 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;
};
于 2012-02-09T23:15:35.023 回答