Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.