将类接口转换为类模板

Converting a class interface into a class template

本文关键字:转换 接口      更新时间:2023-10-16

我正在复习一些没有备忘录的旧试卷。我只是想确保我正确理解这一点。

提供模板类的接口

Dictionary <Tkey, TValue>

这是提供的场景

class Dictionary {
    public:
        Dictionary();
        void Add(int key, const string &value);
        string Find (int key) const;
    private:
        vector<int> Keys;
        vector <string> Values;
};

这是我写下的解决方案

class Dictionary {
    public:
        Dictionary();
        void Add(TKey key, const TValue &value);
        TValue Find (TKey key) const;
    private:
        vector <Dictionary> Keys;
        vector <Dictionary> Values;
};

这对我来说似乎是正确的。我还没有为此编译驱动程序,因为我只想确保我在给定模板类的情况下正确理解这一点。

我想最后两行的矢量是我想确保我写得正确的。

谢谢你抽出时间。

您应该简单地按照您的说明进行操作:

template<typename Tkey, typename TValue> // <<<<<<<<
class Dictionary {
public:
    Dictionary();
    void Add(TKey key, const TValue &value);
    TValue Find (TKey key) const;
private:
    vector <TKey> Keys; // <<<<<<<<
    vector <TValue> Values; // <<<<<<<
};

或者更好(因为很难将这些向量成员适当地关联起来):

template<typename Tkey, typename TValue> // <<<<<<<<
class Dictionary {
public:
    Dictionary();
    void Add(TKey key, const TValue &value);
    TValue Find (TKey key) const;
private:
    vector <std::pair<TKey,TValue>> dict; // <<<<<<<
};

此转换是不完整的,并且有点不正确。

要使其完整,请确保该类实际上是一个类模板,即存在

template <typename TKey, typename TValue>
class Dictionary {
    ...
};

校正是使两个向量取关键帧和值。目前,两个向量都设置为存储Dictionary元素,这不是您所需要的:第一个向量应该包含TKey元素,而第二个向量应该容纳TValue s。一旦开始实现Dictionary<TKey,TValue>::Find方法,您就会发现这个缺点。