OmniSciDB  2e3a973ef4
string_view_unordered_map.h
Go to the documentation of this file.
1 #pragma once
2 
3 //
4 // adapted and updated from example by https://github.com/facontidavide
5 // provides optimized find() and try_emplace() without std::string reallocation
6 //
7 
8 #include <string>
9 #include <string_view>
10 #include <unordered_map>
11 
12 template <typename ValueT>
13 class string_view_unordered_map : public std::unordered_map<std::string, ValueT> {
14  public:
15  using MapT = typename std::unordered_map<std::string, ValueT>;
16 
17  auto find(std::string_view key) const {
18  tmp_key_.reserve(key.size());
19  tmp_key_.assign(key.data(), key.size());
20  return MapT::find(tmp_key_);
21  }
22 
23  auto find(const std::string& key) const { return MapT::find(key); }
24 
25  auto find(const char* key) const {
26  tmp_key_.assign(key);
27  return MapT::find(tmp_key_);
28  }
29 
30  template <typename... ArgsT>
31  auto try_emplace(std::string_view key, ArgsT&&... args) {
32  tmp_key_.reserve(key.size());
33  tmp_key_.assign(key.data(), key.size());
34  return MapT::try_emplace(tmp_key_, std::forward<ArgsT>(args)...);
35  }
36 
37  template <typename... ArgsT>
38  auto try_emplace(const std::string& key, ArgsT&&... args) {
39  return MapT::try_emplace(key, std::forward<ArgsT>(args)...);
40  }
41 
42  template <typename... ArgsT>
43  auto try_emplace(const char* key, ArgsT&&... args) {
44  tmp_key_.assign(key);
45  return MapT::try_emplace(tmp_key_, std::forward<ArgsT>(args)...);
46  }
47 
48  private:
49  thread_local static std::string tmp_key_;
50 };
51 
52 template <typename ValueT>
53 thread_local std::string string_view_unordered_map<ValueT>::tmp_key_;
auto try_emplace(std::string_view key, ArgsT &&... args)
typename std::unordered_map< std::string, ValueT > MapT
auto find(const std::string &key) const
auto find(const char *key) const
auto find(std::string_view key) const
static thread_local std::string tmp_key_
auto try_emplace(const char *key, ArgsT &&... args)
auto try_emplace(const std::string &key, ArgsT &&... args)