簡體   English   中英

如何在C ++中為不同的模板類型使用不同的類定義? (類重載?)

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

我想做的是制作一個哈希表。 為了提高效率,我希望它根據數據類型的不同而有效。 例如:int的二次探測方法,字符串的單獨鏈接方法。

我發現我可以使用typeid()函數來比較typename的模板。 我可以在類的定義中使用它,但我擔心它會減慢程序的速度。

我覺得類“重載”可以解決這個問題。 但我從來沒有聽說過“類重載”。 你認為解決這個問題的正確方法是什么?

謝謝。

“但我從來沒有聽說過”班級超載“。你認為解決這個問題的正確方法是什么?”

您可以為其界面使用模板類和特化(重載):

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 {
};

至於后一個提議,您甚至可以將其擴展為基於策略的設計模式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM