c++ - 模板和重载

标签 c++ templates overloading overload-resolution class-template

  template<class Key1, class Key2, class Type> class DualMultimapCache
  {
  public:
     std::list<std::reference_wrapper<Type>> get(Key1 const & key);
     std::list<std::reference_wrapper<Type>> get(Key2 const & key);
     template<class ...Args> Type & put(Key1 const & key, Args const & ...args);
     template<class ...Args> Type & put(Key2 const & key, Args const & ...args);
  };

在这里,我有一个类的公共(public)接口(interface)。底层数据结构无关紧要。当 Key1Key2 是不同类型时,一切都会正常工作。如果它们最终是同一类型,则重载很可能是不可能的。我的想法对吗?

如果我是,有没有办法在保持签名尽可能干净的同时分离重载?

编辑:这里有一个更深入的示例

  template<class Key1, class Key2, class Type> class DualMultimapCache
  {
  public:
     std::list<std::reference_wrapper<Type>> get(Key1 const & key);
     std::list<std::reference_wrapper<Type>> get(Key2 const & key);
     template<class ...Args> Type & put(Key1 const & key, Args const & ...args);
     template<class ...Args> Type & put(Key2 const & key, Args const & ...args);

  private:
     std::unordered_multimap<Key1, std::reference_wrapper<Type>> map_Key1; 
     std::unordered_multimap<Key2, std::reference_wrapper<Type>> map_Key2;
  };

  template<class Key1, class Key2, class Type>
  std::list<std::reference_wrapper<Type>> DualMultimapCache<Key1, Key2, Type>::get(Key1 const & key)
  {
     auto its = map_Key1.equal_range(key);

     if (its.first == map.cend() && its.second == map.cend())
        throw std::out_of_range();
     else
        return { its.first, its.second };
  }

  template<class Key1, class Key2, class Type>
  std::list<std::reference_wrapper<Type>> DualMultimapCache<Key1, Key2, Type>::get(Key2 const & key)
  {
     auto its = map_Key2.equal_range(key);

     if (its.first == map.cend() && its.second == map.cend())
        throw std::out_of_range();
     else
        return { its.first, its.second };
  }

最佳答案

您可以针对相同键类型的情况部分特化模板,例如

template <typename Key, typename Type>
class DualMultimapCache<Key, Key, Type>
{
public:
   std::list<std::reference_wrapper<Type>> get(Key const & key);
   template<class ...Args> Type & put(Key const & key, Args const & ...args);
};

关于c++ - 模板和重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47755047/

相关文章:

c++ - <iostream> 与 <iostream.h> 与 "iostream.h"

c++ - 在 C++ 中,我可以使用来自不同文件的值安全地初始化 unordered_map 吗?

c++ - 如何将浮点值插入到 C++ 中的映射中?

c++ - 多种类型的别名模板

java - 在 Java 中重载内部接口(interface)

c++ - 强制特定类型的函数模板/函数重载

c++ - 将 Perl 与已编译的 C 库一起使用?

c++ - 非模板类方法的条件模板特化

c++ - EASTL 性能

C++重载