如何在 C++ 中对不同的模板类型使用 class 的不同定义? (Class 超载?)

How can I use different definition of class for different template type in C++? (Class Overloading?)

我想做的是做一个散列table。为了提高效率,我希望它根据数据类型以不同方式工作。例如:整数的二次探测方法,字符串的单独链接方法。

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

我觉得"Class Overloading"这样的东西可以解决这个问题。但是我从来没有听说过"Class Overloading"。你认为解决这个问题的正确方法是什么?

谢谢。

"But I've never heard of "Class Overloading". What is the right way to solve this problem do you think?"

您可以使用模板 class 及其接口的专业化(重载):

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
} 

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

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 模式。