I want to implement family of functions like this:
template <class T>
T GetValue(const TObject& obj, const std::string& field);
template <>
int GetValue<int>(…) {…}
template <>
float GetValue<float>(…) {…}
// Any DerivedString is derived from BaseString
template <class DerivedString>
DerivedString GetValue<DerivedString>(const TObject& obj, const std::string& field) {…} // ← how?
Where the last specialization (or something else) will be called for all types derived from some BaseString type.
The main goal is to be able to call:
GetValue<int>(…);
GetValue<float>(…);
GetValue<BaseString>(…);
GetValue<StrongStringType1>(…);
GetValue<StrongStringType2>(…);
Without specializing function for each derived type.
Function templates can't be partially specialized.
Your options are:
if constexprin it.I'd go with (3).
For (2), to make the "any derived class" overload, any form of SFINAE will work, e.g.:
For
intandfloat, I'd perhaps replace specializations with overloads too, just to be consistent: