How to specialize a template class method for a specific type?

  1. You should make both the overloading of print() to function template (to make SFINAE working), otherwise the non-template function is always preferred.

  2. You should let print() taking its own template type parameter; type cheking shouldn't be performed on the class template parameter T directly, function templates overload resolution and SFINAE are performed on the function templates themselves, the class template doesn't involve in.

  3. You can move the part of std::enable_if to the return type.

  4. You should change the order specified to std::is_base_of (i.e. std::is_base_of<Bar, X>, not std::is_base_of<X, Bar>) if you want the type to be Bar or the derived class of Bar.

e.g.

template <typename X = T>
typename std::enable_if<std::is_base_of<Bar, X>::value>::type print() {
  t.print();
}

template <typename X = T>
typename std::enable_if<!std::is_base_of<Bar, X>::value>::type print() {
  std::cout << t << std::endl;
}

LIVE