模板模板参数与函数模板的等效行为

时间:2014-05-28 02:49:48

标签: c++ templates c++11 template-templates boost-optional

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

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

我知道功能模板不允许使用模板模板参数。但还有另一种方法可以达到同样的效果吗?

2 个答案:

答案 0 :(得分: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;
  }
}

Live demo

答案 1 :(得分: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;
  }
}