Quantcast
Channel: User HolyBlackCat - Stack Overflow
Viewing all articles
Browse latest Browse all 1262

Answer by HolyBlackCat for How to define a template function for a base-type and other unrelated types?

$
0
0

Function templates can't be partially specialized.

Your options are:

  1. One big function with a bunch of if constexpr in it.
  2. Overloading the function instead of specializing.
  3. Wrapping the function in a class template (making the function itself non-template), and specializing the whole class. You can then provide a function that calls into it, for a nicer syntax.

I'd go with (3).

For (2), to make the "any derived class" overload, any form of SFINAE will work, e.g.:

template <std::derived_from<MyStringBase> DerivedString>DerivedString GetValue<DerivedString>(const TObject &obj, const std::string &field) {...}

For int and float, I'd perhaps replace specializations with overloads too, just to be consistent:

template <std::same_as<int>>int GetValue(const TObject& obj, const std::string& field);

Viewing all articles
Browse latest Browse all 1262

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>