我有一个工作的双向映射(一对一映射)类,如下所示:
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_;
};
Run Code Online (Sandbox Code Playgroud)
我已经能够实现该insert功能。现在我想实现一个retrieve功能,例如,如果用户通过类型的值T1比如说t1,它会返回*map1_[t1],同样如果他们通过类型的值T2比如说t2,它会返回*map2_[t2]。可以保证类型T1不会与类型相同,T2因此如何通过检查类型来使其返回值?
如果可以使用C ++ 17,则您的检索函数将如下所示
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
}
Run Code Online (Sandbox Code Playgroud)
如果您不能使用C ++ 17,那么我只会写2个重载,例如
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
}
Run Code Online (Sandbox Code Playgroud)