Returning a value depending on the type of the template parameter

Viewed 64

I have a working bidirectional map (one-to-one mapping) class as follows:

template <typename T1, typename T2>
class BiMap
{
public:
    void insert(const T1& a, const T2& b);
private:
    std::map<T1, T2*> map1_;
    std::map<T2, T1*> map2_;
};

I have been able to implement the insert function. Now I want to implement a retrieve function such that if user passes value of type T1 say t1, it'll return *map1_[t1] and similarly if they pass value of type T2 say t2, it'll return *map2_[t2]. It is guaranteed that type T1 will not be the same as type T2 so how can I make it return a value by checking it's type?

1 Answers

If you can use C++17 your retrieve function would look like

template <typename T>
auto retrieve(T const& key)
{
    static_assert(std::is_same_v<T, T1> || std::is_same_v<T, T2>, "Key type is not in map");
    if constexpr (std::is_same_v<T, T1>)
        return *map1_.at(key); // or whatever you actually want to return
    else
        return *map2_.at(key); // or whatever you actually want to return
}

If you can't use C++17 then I would just write 2 overloads like

auto retrieve(T1 const& key)
{
    return *map1_.at(key); // or whatever you actually want to return
}
auto retrieve(T2 const& key)
{
    return *map2_.at(key); // or whatever you actually want to return
}
Related