【问题标题】:template functions with multiple templates for specific data type like string?具有特定数据类型(如字符串)的多个模板的模板函数?
【发布时间】:2018-10-26 01:32:15
【问题描述】:
template <typename Key, typename E>
class BST : public Dictionary<Key, E>
{
    .....
    E FindHelp(BSTNode<Key, E>*, const Key&) const;
    template <typename Key>
    std::string FindHelp(BSTNode<Key, std::string> *root, const Key &k) const;
    ....
};

template <typename Key>
std::string BST<Key, std::string>::FindHelp(BSTNode<Key, std::string> *root, const Key &k) const
{
    if (root == nullptr) return "Not Found!"; // Empty tree
                                   // If smaller than the root go left sub tree
    if (k < root->key()) return FindHelp(root->Left(), k);
    // If bigger than the root go right tree
    if (k > root->key()) return FindHelp(root->Right(), k);
    // If equal to the root return root value
    else return root->Element();
}

当我像这样编写定义时,我想添加一个处理特定数据类型(如 std::string)的函数

错误 C2244:“BST::FindHelp”:无法匹配 现有声明的函数定义

【问题讨论】:

    标签: c++ function oop templates


    【解决方案1】:

    没有偏函数模板特化。您只能对类使用部分模板特化,因此您必须先对 BST 类进行部分特化。

    template <typename Key, typename E>
    class BST : public Dictionary<Key, E>
    {
        E FindHelp(BSTNode<Key, E>*, const Key&) const;
    };
    
    template<typename Key>
    class BST<Key, std::string> : public Dictionary<Key, std::string>
    {
        std::string FindHelp(BSTNode<Key, std::string>*, const Key&) const;
    };
    
    template <typename Key>
    std::string BST<Key, std::string>::FindHelp(BSTNode<Key, std::string> *root, const Key &k) const
    {
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-28
      • 2014-09-16
      • 2017-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-25
      • 2022-01-21
      相关资源
      最近更新 更多