Search code examples
c++templatestemplate-specializationspecialization

Match a template pattern only if another pattern is matched


I have a template function defined only for some types:

template<typename T, std::enable_if_t<std::is_pod_v<T>, bool> = true >
void serialize(const T & t) { /*serialize POD*/ }

template<>
void serialize(const std::string  & t) { /*serialize string*/ }

//....

And I would like to add a std::vector specialization that matches only if T can be serialized

template<typename T /*, is_serializable<T> */>
void serialize(const std::vector<T> & t) { /*do something*/ }

How can I make this one matching only if T himself matches a serialize() method?


Solution

  • With C++20 constraints, you might do something like:

    template <typename T>
    void serialize(const std::vector<T>& v)
    requires requires (T inner) {serialize(inner);}
    {
      // serialize vector
      // ...
    }
    

    Demo