【问题标题】:No match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘const std::type_index’)‘operator<<’ 不匹配(操作数类型是 ‘std::ostream’ {aka ‘std::basic_ostream<char>’} 和 ‘const std::type_index’)
【发布时间】: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 &lt;&lt;。
  • 你的意思是std::cout &lt;&lt; i.first.name()?
  • 我不明白,我不需要为 type_index 定义一个运算符来循环 unordered_map 否?
  • 不循环,但您正在尝试输出它。没有为 std::type_index 定义输出运算符
  • @HugoS 不,您需要operator&lt;&lt; 才能将类型输出到std::ostream

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 2016-12-01
    • 1970-01-01
    相关资源
    最近更新 更多