其他分享
首页 > 其他分享> > C boost enable_if问题

C boost enable_if问题

作者:互联网

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

我有一个简单的类结构 – 基础类,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_if和boost :: 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.

标签:c,templates,boost,enable-if
来源: https://codeday.me/bug/20190726/1545274.html