Ask Your Question
2

What is the process to generate a template for a map or unordered_map that can accept either char or string input?

asked 2023-05-09 21:21:38 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-05-09 21:40:01 +0000

devzero gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-05-09 21:21:38 +0000

Seen: 14 times

Last updated: May 09 '23