views:

101

answers:

2

Hello!

Do I have any way to simplify the following statements? (probably, using boost::enable_if).

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;
};

I want to write the same statement using one template specialization of translator_between.

An example (pseudocode) of what I want to be able to write:

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;
};

Any way to achieve this using boost::enable_if and boost::is_base_of?

+2  A: 

I don''t think boost::enable_if helps, because SFINAE seems to be rather about selecting between function overloads.

You can of course use templates with bool parameters to refine the choice:

#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
}
UncleBens
+1  A: 

First, you'll have to pick your choice among:

  • is_base_of
  • is_convertible

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;
};

Since there is no overload resolution taking place here, you don't need enable_if.

Matthieu M.