简体   繁体   中英

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 wich 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<char>’} and ‘const std::type_index’)
       std::cout << i.first << i.second << std::endl;

Here is my loop who 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM