【问题标题】:c++ template: Create a specialized function for a specific data typec++ 模板:为特定数据类型创建专用函数
【发布时间】:2012-11-16 22:04:57
【问题描述】:

我在下面有一个模板Node,用于在数组中存储一些数据。在添加之前,我想检查是否存在具有相同值的条目(我的插入逻辑需要它)。对于字符串类型,我想实现一个具体的比较方法。

template <class T> class Node
{
private:
    short noOfEntries;
    T data[MAX_VALUES];
public:
    Node () { noOfEntries = 0; }
    int Compare(int index, T *key);
    int Insert(T *key);
};

template <class T>
int Node<T>::Compare(int index, T *key)
{
    if(data[index] > *key)
        return 1;
    else if(data[index] == *key)
        return 0;
    return -1;
}

template <>
class Node <string> {
  public:
    int Compare(int index, string *key)
    {
        return (data[index].compare(*key));
    }
};

这会产生错误,因为属性 'data' 和 'noOfEntries' 不在类 Node &lt;string&gt; 中。 看来我必须将 Node 中的所有属性都放到字符串的专用版本中。方法也一样。

有没有更好的方法让我只为 Node 定义一个插入方法,该方法将根据 T 的实际类型调用正确的 compare() 方法?我想避免重复方法。

【问题讨论】:

  • 具有不同字符特征或分配器的字符串呢?

标签: c++ string templates generics


【解决方案1】:

只专注于一个成员:

template <> int Node<std::string>::Compare(int index, std::string *key)
    {
        return (data[index].compare(*key));
    }

更惯用的方法是使用比较策略模板参数,或者可能是描述元素类型的默认比较策略的特征。

【讨论】:

  • 这太棒了。我非常感谢你帮助我:) 你是从哪里学到的?我是新手,想提高自己。
  • 我推荐“C++ 模板完整指南”。另请参阅我们的definitive book list
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-02
  • 2017-04-04
  • 2019-04-23
  • 1970-01-01
  • 1970-01-01
  • 2012-03-11
相关资源
最近更新 更多