Here's an example of a template for a map or unordered_map that can accept either char or string input:
#include <unordered_map>
#include <string>
template<typename T>
using my_map = std::unordered_map<T, int>;
template<>
using my_map<std::string> = std::unordered_map<std::string, int>;
int main() {
my_map<char> m1 = {{'a', 1}, {'b', 2}};
my_map<std::string> m2 = {{"hello", 3}, {"world", 4}};
return 0;
}
In this example, we define a template alias my_map
which defaults to an std::unordered_map
with a key of type T
and a value of type int
. However, we also specialize my_map
for the case where T
is std::string
, using the actual std::unordered_map<std::string, int>
type. This allows us to handle both char
and std::string
keys seamlessly without having to write any duplicate code.
Note that this is just one possible approach, and there may be other ways to achieve the same goal depending on your specific requirements.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-05-09 21:21:38 +0000
Seen: 15 times
Last updated: May 09 '23
What is the method to transmit a map<String,Map<String,Integer>> along with application.properties?
What is the procedure to remove all markers and layers from a Leaflet map in order to add new ones?
How can I get the choropleth map to display on Jupyter Notebook when using Plotly Express?
How can I show several locations on a Leaflet map using GraphHopper?
How do I obtain Latin-1 codes for particular characters?
How can one go over a key/value map object by repeatedly executing its elements?
How can one display grid labels on a Southpolar stereographic map in cartopy?
What is a responsive image map?
What is the process of including a map<String,Map<String,Integer>> in application.properties?