根据模板参数的类型返回值

luc*_*eon 2 c++ templates

我有一个工作的双向映射(一对一映射)类,如下所示:

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因此如何通过检查类型来使其返回值?

Nat*_*ica 9

如果可以使用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)

  • @lucieon我个人喜欢两个重载解决方案,因为它更短并且更容易理解。它还使您的代码可以在更多的实现上进行编译。通常,如果只有少量重载,我只会使用第一种方法。 (4认同)