c++ - 使用一个函数打印 map 和 unordered_map 对

标签 c++ c++11 templates

我已经有了这个工作代码:

template <typename T1, typename T2>
std::ostream& operator<<(std::ostream &out, std::map<T1, T2> &map){
        for (auto it = map.begin(); it != map.end(); ++it) {
                out <<  it-> first << ", " << it->second << '\n';
        }
        return out;
}
template <typename T1, typename T2>
std::ostream& operator<<(std::ostream &out, std::unordered_map<T1, T2> &map){
        for (auto it = map.begin(); it != map.end(); ++it) {
                out <<  it-> first << ", " << it->second << '\n';
        }
        return out;
}

如您所见,这两个函数几乎相同。有没有办法删除一个并只使用一个抽象函数?

最佳答案

你确实可以:这是一个函数模板,适用于任何具有 value_type 的可迭代类型那是一个std::pair<> .这不仅适用于 std::map<>std::unordered_map<> , 还有 std::vector<std::pair<>> , boost::container::list<std::pair<>>等:

namespace detail {
    template<typename>
    struct is_pair : std::false_type { };

    template<typename T1, typename T2>
    struct is_pair<std::pair<T1, T2>> : std::true_type { };
}

template<
    // collection type
    typename T,
    // ensure value_type exists
    typename VT = typename T::value_type,
    // ensure value_type is some std::pair<>
    typename std::enable_if<detail::is_pair<VT>{}>::type* = nullptr
>
auto operator <<(std::ostream& out, T const& coll)
// ensure begin(coll) and end(coll) are legal
-> decltype(void(begin(coll)), void(end(coll)), out) {
    for (auto it = begin(coll); it != end(coll); ++it) {
        out << it->first << ", " << it->second << '\n';
    }
    return out;
}

Online Demo

关于c++ - 使用一个函数打印 map 和 unordered_map 对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40609412/

相关文章:

c++ - 使用 Codeblocks 和 Cmake Linux 编译 GLFW

macos - 指定编译器 Homebrew 安装

c++ - 类数学 vector 操作的自动符号约定

c++ - 有没有办法延长 C++ 中临时对象的生命周期?

c++ - 获取 std::map 中的最小键

c++ - 为另一个类专门化模板类的运算符<<

java - 再次调用同一个 Play 模板时,变量的作用域如何?

c++ - 如何在 CLion 中包含 ASIO C++?

c++ - 引用宏的扩展值

c++ - Qt - QPropertyAnimation 中存在错误?