How to specialize a template class method for a specific type?
You should make both the overloading of
print()
to function template (to make SFINAE working), otherwise the non-template function is always preferred.You should let
print()
taking its own template type parameter; type cheking shouldn't be performed on the class template parameterT
directly, function templates overload resolution and SFINAE are performed on the function templates themselves, the class template doesn't involve in.You can move the part of
std::enable_if
to the return type.You should change the order specified to
std::is_base_of
(i.e.std::is_base_of<Bar, X>
, notstd::is_base_of<X, Bar>
) if you want the type to beBar
or the derived class ofBar
.
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;
}