0

I have two std:map where one's key is of type CustomClass1 and another's key is of type CustomClass2, but their value's type is the same, std::string.

//first map
std::map<CustomClass1, std::string>
//second map
std::map<CustomClass2, std::string>

I want to create a template function that takes a key as input that can either be CustomClass1 or CustomClass2, and tries to find the associated string in the map.

I know how to find a value given a key in a map:

map<key, std::string>::iterator iterator = map.find(key);
if(iterator1 != map.end()){
    //value found
}

How can I create such a method with a template function?

zfgo
  • 195
  • 11

2 Answers2

3

With C++17 you can use if constexpr to distinguish between types during compile time.

#include <map>
#include <string>
#include <type_traits>

struct CustomClass1 {};
struct CustomClass2 {};
//first map
std::map<CustomClass1, std::string> map1;
//second map
std::map<CustomClass2, std::string> map2;

template<typename KeyType>
void foo(const KeyType& key)
{
    if constexpr(std::is_same_v<KeyType, CustomClass1>)
    {
        // do stuff with map1
        map1[key];
    }
    else if constexpr(std::is_same_v<KeyType, CustomClass2>)
    {
        // do stuff with map2
        map2[key];
    }
}
serkan.tuerker
  • 1,681
  • 10
  • 20
0
template <class Map>
std::string getStringFromMap(const Map& map, const typename Map::key_type& key) {
    auto it = map.find(key);
    if (it != map.end()) {
        return it->second; // string found
    } else {
        return std::string(); // return default value
    }
}

It should work for any std::map. Here typename Map::key_type is key type alias provided by std::map template, so actual type of 2nd parameter key is extracted from map template instantiation. Keyword typename tells the compiler that Map member key_type must be a type.