如何制作一个接受地图或 unordered_map 的函数?

Cla*_*diu 3 c++ templates

我正在实现一些基于模板的序列化。我为 实现了模板化函数std::map,但现在我使用的是std::unordered_map. 我宁愿不复制和粘贴整个函数,而只是更改参数类型。有没有办法制作一个只需要一张地图或一张无序地图的模板?

Pio*_*cki 5

template <typename MAP>
void generic_foo(MAP& map)
{
    // generic implementation of your function
    // that works with unordered_map and map

    using K = typename MAP::key_type;
    using T = typename MAP::mapped_type;
}

// matches any possible implementation of std::unorderd_map
template <class Key,                                    
          class T,                                   
          class Hash,                       
          class Pred,                  
          class Alloc>
void foo(std::unordered_map<Key, T, Hash, Pred, Alloc>& m)
{
    // signature matched! forward to your implementation
    generic_foo(m);
}

// matches any possible implementation of std::map        
template <class Key,                                    
          class T,                          
          class Compare,                  
          class Alloc>
void foo(std::map<Key, T, Compare, Alloc>& m)
{
    // signature matched! forward to your implementation
    generic_foo(m);
} 
Run Code Online (Sandbox Code Playgroud)

LIVE DEMO