将类接口转换为类模板
Converting a class interface into a class template
我正在复习一些没有备忘录的旧试卷。我只是想确保我正确理解这一点。
提供模板类的接口
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
方法,您就会发现这个缺点。
相关文章:
- 从常量字符*、字符*参数到标准::字符串的直接转换接口
- 在构造函数处将类对象强制转换为接口始终返回 NULL
- 尝试向 COM 对象添加另一个接口时出现静态强制转换错误 C2440
- 将下一个(),hasNext()迭代界面转换为begin(),end()接口
- 如何将接口对象强制转换为特定的继承对象
- C++ 从接口和强制转换的多重继承
- 在 C# 中加载 COM 对象会引发异常"无法将类型'System.__ComObject'的 COM 对象强制转换为接口类型...",但C++或 VB 不会
- C++从接口类到子类的转换无效
- 如何从C类中告知/强制转换for C++接口的实例
- 从Const引用接口到派生类的转换
- 向上转换到超类或接口
- CLR 探查器:COM 样式的强制转换和从派生接口调用函数
- 具有扩展接口的派生类的集合.如何在没有动态强制转换的情况下访问派生接口
- 有没有办法将 COM 接口 GUID 转换为接口的字符串名称
- 使用接口包装库,而无需向下转换
- 如何为一个简单的转换例程设计一个接口
- opencv c与c++接口转换表
- 将类接口转换为类模板
- 沿着模板类使用非虚接口向下转换
- 静态转换接口类到内部引擎实现