c++ - 与 ‘operator<<’ 不匹配(操作数类型为 ‘std::ostream’ {aka ‘std::basic_ostream<char>’ } 和 ‘const std::type_index’ )

标签 c++ loops unordered-map visitor-pattern

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

我想解析我的 unordered_map,其中包含 type_indexfunction 变量,但我收到一个我什至不理解的编译错误在阅读了很多相关主题后。

error: no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream’} and ‘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");
    }
  }
};

如果有人知道如何解决这个问题,我很乐意接受!谢谢

最佳答案

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

关于c++ - 与 ‘operator<<’ 不匹配(操作数类型为 ‘std::ostream’ {aka ‘std::basic_ostream<char>’ } 和 ‘const std::type_index’ ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58997858/

相关文章:

excel - 在一个数组中找到 2 个元素,它们在一个简单的方程中给出一个目标结果

c++ - boost::unordered_map 缺少像 std::unordered_map 这样的 reserve()

c++ - 优先队列图

c++ - 列表框属性值未出现在 C++ 自定义操作 Wix 中?

c++ - 解析 CSS 样式表

javascript - 如何在javascript函数中传递两个 View 模型参数

c++ - 通过其他字符串索引字符串

c++ - 为什么我的用于运行带障碍物传感器的蓝牙控制机器人的 Arduino 代码无法正常工作?

c++ - 将米转换为英尺到英寸 C++?

c++ - 迭代器循环与索引循环