C ++ boost enable_if问题 [英] C++ boost enable_if question

查看:181
本文介绍了C ++ boost enable_if问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有办法简化以下语句吗? (可能使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆