Question

This question is similar to: c++ template specialization for all subclasses Instead of a templated function, now I have a member function of a templated class which needs to do different things based on base-class of the class-template

template<typename T>

class xyz
{
  void foo()
  {
     if (T is a subclass of class bar)
        do this
     else
        do something else
  }

}

I couldn't find an easy to understand tutorial for boost::enable_if. so i cannot get the syntax right for this minor modification

Was it helpful?

Solution

You have can use Tag Dispatching :

template <typename T> class   xyz  
{
  public:
  void foo()  
  {
     foo( typename boost::is_base_of<bar,T>::type());
  }

  protected:
  void foo( boost::mpl::true_ const& )
  {
    // Something
  }

  void foo( boost::mpl::false_ const& )
  {
    // Some other thing
  }
};

Note that tag dispatching is usually better than SFINAE using enable_if, as enable_if require a linear number of template instantiation before selecting the proper overload.

In C++11, you can use the std:: equivalent of these boost meta-functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top