c++ - 我如何创建一个接受 map 或 unordered_map 的函数?

标签 c++ templates

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

最佳答案

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

LIVE DEMO

关于c++ - 我如何创建一个接受 map 或 unordered_map 的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25749917/

相关文章:

C++模板函数选择

c++ - 在带有 Visual Studio 的 Windows 上使用 swig -go

c++ - 如何在c++中包含头文件?

c++ - 从模板模板方法参数中获取类型

c++ - “Partial application” 模板参数

c++ - 将 mp3 解码为整数流

c++ - 将名称和数字输出到文件 C++

c++ - Boost::asio udp socket - 我应该如何使用 API 来允许取消读取?

javascript - Angular JS 错误 : $compile:tpload: Failed to load template:

c# - 模板中的服务器控件如何对数据上下文敏感?