Search code examples
c++templatesc++11template-templatesboost-optional

Equivalent behaviour for template template arguments to function templates


I am trying to write code like this:

template <typename K, typename T, template <typename, typename> class C>
boost::optional<T> search(const C<K, T>& dict,
                          const K& key)
{
  auto it = dict.find(key);

  if (it != dict.end()) {
    return it->second;
  } else {
    return boost::none;
  }
}

The hope was to be able to call the above function on a variety of containers (std::[unordered_][multi]map) with the dictionary interface like:

std::map<std::string, Foo> strToFoo;
auto val = search(strToFoo);

I know that function templates do not allow template template parameters. But is there another way to achieve the same effect?


Solution

  • The problem with your code is that the containers that you want this to work for - (unordered_)(multi)map - have 4 or 5 template parameters, while your code only expects 2. Use template template parameters and variadic templates together to allow for the extra template parameters.

    template <typename Key, typename Value, 
              template <typename, typename, typename...> class C, 
              typename... Args>
    boost::optional<Value> search(const C<Key, Value, Args...>& dict,
                                  const Key& key)
    {
      auto it = dict.find(key);
    
      if (it != dict.end()) {
        return it->second;
      } else {
        return boost::none;
      }
    }
    

    Live demo