简体   繁体   中英

How to unfold a template to string when the possible type be float or string?

In C++, i want to build a string only container from a template.

For example:

template<typename T>
void show(const T & t) {  // the T can be map<string, string> or <string, float> or <string, int>
  std::unordered_map<std::string, std::string> r;
  for (const auto & i : t) {
     const auto & j = i.first;
     const auto & k = i.second;  //  TODO: how to
     // make k as string, possible type of k can be 
     // int float or string???
     // put them into r
  }
  return r;
}

How can i implement this?

IF you can use C++17, then constexpr if statement is what you want. That would give you

template<typename T> // the T can be map<string, string> or <string, float> or <string, int>
std::unordered_map<std::string, std::string> show(const T & t) {  
  std::unordered_map<std::string, std::string> r;
  for (const auto & i : t) {
     const auto & j = i.first;
     const auto & k = i.second;
     if constexpr(std::is_same_v<std::decay_t<decltype(k)>, std::string>)
       r.insert(std::make_pair(j, k));
     else
       r.insert(std::make_pair(j, std::to_string(k)));
  }
  return r;
}

If you want to use C++11, you can use a template plus an overload to handle the dispatch like

template<typename T>
std::unordered_map<std::string, std::string> show(const std::map<std::string, T> & t) {  
  std::unordered_map<std::string, std::string> r;
  for (const auto & i : t) {
     const auto & j = i.first;
     const auto & k = i.second;
     r.insert(std::make_pair(j, std::to_string(k)));
  }
  return r;
}

std::unordered_map<std::string, std::string> show(const std::map<std::string, std::string> & t) {  
  std::unordered_map<std::string, std::string> r;
  for (const auto & i : t) {
     const auto & j = i.first;
     const auto & k = i.second;
     r.insert(std::make_pair(j, k));
  }
  return r;
}

This works because when a std::map<std::string, std::string> is passed, it is an exact match to the non-function template, and that takes precedence over the function template.

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