嘗試輸出值可以是任何資料型別的地圖物件。嘗試了以下方法:
#include <iostream>
#include <unordered_map>
#include <any>
std::unordered_map<std::string, std::any> example = {
{"first", 'A'},
{"second", 2},
{"third", 'C'}
};
std::ostream &operator<<(std::ostream &os,
const std::any &m) {
for (auto &t : example) {
os << "{" << t.first << ": " << t.second << "}\n";
}
return os;
}
int main()
{std::cout << example;
return 0;
}
但是,獲得無限回圈的價值。
uj5u.com熱心網友回復:
沒有列印任意std::unordered_map<std::string, std::any>. 它可能包含不可列印的內容,并且您已經丟棄了有關內容實際型別的資訊。您需要將這些資訊保存在某個地方。
#include <string>
#include <iostream>
#include <unordered_map>
#include <any>
#include <utility>
template <typename T>
std::ostream & print_any(std::ostream & os, const std::any & any) {
return os << std::any_cast<const std::decay_t<T> &>(any);
}
class any_printable {
using print_t = std::ostream & (*)(std::ostream &, const std::any &);
std::any value;
print_t print;
public:
template <typename T>
any_printable(T&& t) : value(std::forward<T>(t)), print(print_any<T>) {}
friend std::ostream & operator<<(std::ostream & os, const any_printable & ap) {
return ap.print(os, ap.value);
}
};
std::ostream &operator<<(std::ostream &os, const std::unordered_map<std::string, any_printable> &map) {
for (auto & [key, value] : map) {
os << "{" << key << ": " << value << "}\n";
}
return os;
}
int main() {
std::unordered_map<std::string, any_printable> example = {
{"first", 'A'},
{"second", 2},
{"third", 'C'}
};
std::cout << example;
}
在coliru上看到它
uj5u.com熱心網友回復:
另一種選擇是將每種型別對應的列印函式注冊到哈希表中,type_index(any::type)作為運行時訪問相應列印函式的鍵。
#include <any>
#include <iostream>
#include <unordered_map>
#include <typeindex>
template<class... Ts>
auto gen_any_printer = std::unordered_map{
std::pair{
std::type_index(typeid(Ts)),
[](std::ostream& os, const std::any& a) -> auto&
{ return os << std::any_cast<Ts const&>(a); }
}...
};
std::ostream& operator<<(std::ostream& os, const std::any& a) {
const static auto any_printer = gen_any_printer<char, int, const char*>;
return any_printer.at(std::type_index(a.type()))(os, a);
}
std::ostream& operator<<(
std::ostream& os, const std::unordered_map<std::string, std::any>& m) {
for (const auto& [key, value] : m)
os << "{" << key << ": " << value << "}\n";
return os;
}
int main() {
std::unordered_map<std::string, std::any> example = {
{"first", 'A'}, {"second", 2}, {"third", "hai"}
};
std::cout << example;
}
演示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/366721.html
上一篇:為什么支持C 11及更高版本的C 編譯器需要Boost.SmartPtr?
下一篇:多載輸出運算子未按預期作業
