如何将map和unordered_map作为同一个对象处理

时间:2014-06-21 01:28:22

标签: c++ c++11 refactoring

我正在制作某种用于打印数据的库,我有这段代码。

struct io {
    template<class U, class V>
    static inline void print_map(const std::unordered_map<U, V>& m, const string& delimiter = " ") {
        std::stringstream sin;
        for (const auto& p : m) sin << "(" << p.first << ", " << p.second << ")" << delimiter;
        print_stream(sin, delimiter.size());
    }

    template<class U, class V>
    static inline void print_map(const std::map<U, V>& m, const string& delimiter = " ") {
        std::stringstream sin;
        for (const auto& p : m) sin << "(" << p.first << ", " << p.second << ")" << delimiter;
        print_stream(sin, delimiter.size());
    }
private:
    static void print_stream(const std::stringstream& sin, const int ignore) {
        const std::string result = sin.str();
        std::cout << result.substr(0, result.size() - ignore) << std::endl;
    }
};

我的问题是,是否有某种方法可以使print_map函数成为单个函数,我不需要重载它,也许是这样的

struct io {
    template<class U, class V>
    static inline void print_map(const maps_super_class<U, V>& m, const string& delimiter = " ") {
        std::stringstream sin;
        for (const auto& p : m) sin << "(" << p.first << ", " << p.second << ")" << delimiter;
        print_stream(sin, delimiter.size());
    }
private:
    static void print_stream(const std::stringstream& sin, const int ignore) {
        const std::string result = sin.str();
        std::cout << result.substr(0, result.size() - ignore) << std::endl;
    }
};

1 个答案:

答案 0 :(得分:3)

您只需使用typename T

替换所有内容即可
template<typename T>
static inline void print_map(const T& m, const string& delimiter = " ") {
    std::stringstream sin;
    for (const auto& p : m) sin << "(" << p.first << ", " << p.second << ")" << delimiter;
    print_stream(sin, delimiter.size());
}