Search code examples
c++loopsunordered-mapvisitor-pattern

No match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘const std::type_index’)


Actually, I'm trying to use the visitor pattern with some templates.

I want to parse my unordered_map which contains type_index and the function variable but I get a compilation error that I don't understand even after reading a lot of topics about it.

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;

Here is my loop which doesn't compile

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

Here is my code snippet with my loop to parse and display what is inside the 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");
    }
  }
};

If anyone has an idea of how to resolve it, I'll gladly take it! Thanks


Solution

  • You should try to print i.first.name() instead of i.first only