我正在制作某种用于打印数据的库,我有这段代码。
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;
}
};
答案 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());
}