1

我正在尝试编写这样的代码:

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;
  }
}

希望能够在(std::[unordered_][multi]map)具有字典接口的各种容器上调用上述函数,例如:

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

我知道函数模板不允许模板模板参数。但是还有其他方法可以达到同样的效果吗?

4

2 回答 2

5

您的代码的问题在于,您希望它适用的容器(unordered_)(multi)map有 4 或 5 个模板参数,而您的代码只需要 2 个。同时使用模板模板参数和可变参数模板以允许额外的模板参数。

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;
  }
}

现场演示

于 2014-05-28T03:20:35.513 回答
1

我现在无法访问编译器,但我认为这样的事情会起作用:

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

  if (it != dict.end()) {
    return it->second;
  } else {
    return boost::none;
  }
}
于 2014-05-28T02:55:22.117 回答