【问题标题】:How can I use different definition of class for different template type in C++? (Class Overloading?)如何在 C++ 中为不同的模板类型使用不同的类定义? (类重载?)
【发布时间】:2015-07-28 17:16:16
【问题描述】:

我想做的是制作一个哈希表。为了提高效率,我希望它根据数据的类型以不同的方式工作。例如:int 的二次探测方法,string 的分离链接方法。

我发现我可以使用typeid()函数来比较模板的typename。我可以在类的定义中使用它,但我担心它会减慢程序的速度。

我觉得像“类重载”这样的东西可以解决这个问题。但我从未听说过“类重载”。你认为解决这个问题的正确方法是什么?

谢谢。

【问题讨论】:

  • 使哈希表类本身成为一个模板,并根据需要对每种类型进行专门化(因为您已经决定要编写所有额外的特定于类型的代码)。老实说,可能会为自己节省一些时间,看看std::unordered_map 是否符合您的喜好。您最终可能会为自己节省大量工作。
  • @WhozCraig 谢谢你的建议,但不幸的是,我的任务的目的是在不使用 std::unordered_map 的情况下制作最快的哈希表ㅠ.ㅠ
  • "type traits" 是另一种根据特定类型选择实现的更细粒度的方法,可以与更大模板的特化结合使用。

标签: c++ templates hashtable overloading


【解决方案1】:

“但是我从来没有听说过“类重载”。你认为解决这个问题的正确方法是什么?”

您可以为它的接口使用模板类和特化(重载):

template<typename T>
class hash_table {
public:
    bool probe(const T& x);
    hash_table<T> chain(const T& x);
};

template<>
bool hash_table<int>::probe(const int& x) {
    // int specific implementation
} 
template<>
bool hash_table<std::string>::probe(const std::string& x) {
    // std::string specific implementation
} 
template<>
hash_table<int> hash_table<int>::chain(const int& x) {
    // int specific implementation
} 
template<>
hash_table<std::string> hash_table<std::string>::chain(const std::string& x) {
    // std::string specific implementation
} 

您还可以使用更灵活的变体,使用基类来提供接口,并使用基于类型的选择器来继承:

template<typename T>
class hash_table_base {
    virtual bool probe(const T& x) = 0;
    virtual hash_table_base<T> chain(const T& x) = 0;
    void some_common_code() {
        // ....
    }
};

class hash_table_int 
: public hash_table_base<int> {
    virtual bool probe(const int& x) {
    }
    virtual hash_table_base<int> chain(const T& x) {
    }
}

class hash_table_string 
: public hash_table_base<std::string> {
    virtual bool probe(const std::string& x) {
    }
    virtual hash_table_base<std::string> chain(const std::string& x) {
    }
}

template <typename T>
struct SelectImpl {
     typedef hash_table_base<T> BaseClass;
};

template<int> struct SelectImpl {
     typedef hash_table_int BaseClass;
};

template<std::string> struct SelectImpl {
     typedef hash_table_sting BaseClass;
};

template<typename T>
class hash_table
: public SelectImpl<T>::BaseClass {
};

对于后一种建议,您甚至可以将其扩展为 Policy based design 模式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-09
    • 2012-12-23
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 2021-11-22
    相关资源
    最近更新 更多