【发布时间】:2019-11-22 16:04:50
【问题描述】:
实际上,我正在尝试将访问者模式与一些模板一起使用。
我想解析包含type_index 和function 变量的unordered_map,但我得到一个编译错误,即使在阅读了很多关于它的主题后我也无法理解。
错误:'operator
这是我没有编译的循环
for (auto i : functions) {
std::cout << i.first << i.second << std::endl;
}
这是我的代码 sn-p 和我的循环来解析和显示 unordered_map 中的内容
template <typename TReturn> struct AnyVisitor {
using typeInfoRef = std::reference_wrapper<const std::type_info>;
using function = std::function<TReturn(std::any &)>;
std::unordered_map<std::type_index, function> functions;
template <typename TArg> void accept(std::function<TReturn(TArg &)> f) {
functions.insert(std::make_pair(std::type_index(typeid(TArg)),
function([&f](std::any &x) -> TReturn {
return f(std::any_cast<TArg &>(x));
})));
for (auto i : functions) {
std::cout << i.first << i.second << std::endl;
}
}
TReturn operator()(std::any &x) {
try {
auto function = functions.at(std::type_index(x.type()));
return function(x);
} catch (...) {
throw std::runtime_error("No visitor registered");
}
}
};
如果有人知道如何解决它,我很乐意接受!谢谢
【问题讨论】:
-
什么不能得到?
std::type_index没有定义operator <<。 -
你的意思是
std::cout << i.first.name()? -
我不明白,我不需要为 type_index 定义一个运算符来循环 unordered_map 否?
-
不循环,但您正在尝试输出它。没有为
std::type_index定义输出运算符 -
@HugoS 不,您需要
operator<<才能将类型输出到std::ostream
标签: c++ loops unordered-map visitor-pattern