简体   繁体   English

当可能的类型为浮点数或字符串时,如何将模板展开为字符串?

[英]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.在 C++ 中,我想从模板构建一个仅字符串的容器。

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.如果您可以使用 C++17,那么constexpr if 语句就是您想要的。 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如果你想使用 C++11,你可以使用一个模板加上一个重载来处理这样的调度

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.这是有效的,因为当传递std::map<std::string, std::string> ,它与非函数模板完全匹配,并且优先于函数模板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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