首页 > 解决方案 > 'operator<<' 不匹配(操作数类型为 'std::ostream' {aka 'std::basic_ostream'} 和 'const std::type_index')

问题描述

实际上,我正在尝试将访问者模式与一些模板一起使用。

我想解析我unordered_map的包含type_indexfunction变量,但是我得到一个编译错误,即使在阅读了很多关于它的主题之后我也不明白。

错误:'operator<<' 不匹配(操作数类型是 'std::ostream' {aka 'std::basic_ostream'} 和 'const std::type_index')std::cout << i.first << i .second << std::endl;

这是我无法编译的循环

for (auto i : functions) {
      std::cout << i.first << i.second << std::endl;
}

这是我的代码片段和我的循环来解析和显示里面的内容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");
    }
  }
};

如果有人知道如何解决它,我很乐意接受!谢谢

标签: c++loopsunordered-mapvisitor-pattern

解决方案


您应该尝试打印i.first.name()而不是i.first仅打印


推荐阅读