Search code examples
c++templatesvariadic-templates

Generic "multi-contains" for maps


I frequently encounter the usecase where I have to check whether a set of keys is contained in a set of nested maps. I currently have an implementation for a number of practical nesting depths that look something like this:

  template< typename Key1T, typename Key2T, typename ValueT >
  bool contains
    ( std::map< Key1T, std::map< Key2T, ValueT > > const & m
    , Key1T                                        const & k1
    , Key2T                                        const & k2
    )
  {
    return m.contains( k1 ) && m.at( k1 ).contains( k2 );
  }

I was wondering if there was a way to implement this as a single function for all possible nesting depths, maybe facilitating variadic templates?


Solution

  • I question the motives behind doing something like this, but here you go:

    template<typename FirstKey, typename InnerMap, typename... RemainingKeys>
    bool contains(std::map<FirstKey, InnerMap> const& m,
                  FirstKey const& firstKey,
                  RemainingKeys const&... remainingKeys)
    {
        auto it = m.find(firstKey);
        if constexpr (sizeof...(remainingKeys) == 0) {
            return it != m.end();
        } else {
            return it != m.end() && contains(it->second, remainingKeys...);
        }
    }
    

    Demo