Given the following base class:
struct ValueType {
String
ToString(String const& format) const;
};
I want this overload to be called for types deriving from ValueType:
String FormatValue(const ValueType& value, const String& format)
{
return value.ToString(format);
}
Otherwise, I want this overload to be called:
template <typename T>
String FormatValue(const T& value, const String& format);
How can I ensure that derived types do not instead call the second overload?
I am not too fond of what you are trying to do for different reasons (including the
ValueTypeinterface, why not useAnyToStringalways?), but at any rate you should be able to solve your problem with SFINAEWhat that code does (once you make it compile 🙂 is inhibiting the template function when the condition is met. When the compiler considers the template as an overload it will try to substitute the type, and the
enable_ifinstantiation will fail to have a nestedtypeif the condition is met, so the substitution fails and the template is discarded. After that, the best overload will be the version that takes aValueTypeobject.