Std :: enable_if, template specialization and inheritance

I would like to ask you for some advice regarding this code. It works, but I think it can be written in a more elegant way. This is C ++ 11 code, so keep that in mind when you compile it;)!

#include <iostream>
#include <type_traits>
#include <typeinfo>

using namespace std;

class A {};
class B: public A {};

class C {};
class D: public C {};

class E: public A, public C {};

template<class T, typename = void>
class Example;

template<class T>
class Example<T, typename enable_if<is_base_of<A, T>::value and not is_base_of<C, T>::value>::type>
{
  public:
    string a() const
    {
      return string(typeid(T).name()) + " have A as base class";
    }
};

template<class T>
class Example<T, typename enable_if<not is_base_of<A, T>::value and is_base_of<C, T>::value>::type>
{
  public:
    string b() const
    {
      return string(typeid(T).name()) + " have C as base class";
    }
};

template<class T>
class Example<T, typename enable_if<is_base_of<A, T>::value and is_base_of<C, T>::value>::type> :
    public Example<A>,
    public Example<C>
{
};

int
main()
{
  Example<B> example1;
  Example<D> example2;
  Example<E> example3;

  cout << example1.a() << endl;
  //cout << example1.b() << endl;   It must raise a compile error
  //cout << example2.a() << endl;   It must raise a compile error
  cout << example2.b() << endl;
  cout << example3.a() << endl;
  cout << example3.b() << endl;
}

      

As you can see, I am trying to write a class template that can handle classes derived from A and C. The problem is that A and C either inherit, as for class E. In fact, we might also have something like this...

template<class T>
class Example<T, typename enable_if<is_base_of<A, T>::value> { /* ... */ };

template<class T>
class Example<T, typename enable_if<is_base_of<C, T>::value> { /* ... */ };

      

... but it will fail if a class (like E) inherits either A or C.

Any ideas for better code? Thanks to

+3


source to share


1 answer


An easier way is to use static_assert

.



template <typename T>
class Example
{
public:
    std::string a() const
    {
        static_assert(std::is_base_of<A, T>::value, "T must derive from A to use a()");
        return std::string(typeid(T).name()) + " have A as base class";
    }

    std::string b() const
    {
        static_assert(std::is_base_of<C, T>::value, "T must derive from C to use b()");
        return std::string(typeid(T).name()) + " have C as base class";
    }
};

      

+4


source







All Articles