How can I use a different class definition for a different type of template in C ++? (Class overload?)
I want to make a hash table. To make it efficient, I want it to work differently depending on the data type. Example: quadratic probing method for int, separate chaining method for string.
I found that I can use a function typeid()
to compare the typename
pattern. I could use it in a class definition, but I'm worried that it will slow down the program.
I feel like something like "Class Overloading" can solve this problem. But I've never heard of "class overloading". What do you think is the correct way to solve this problem?
Thank.
source to share
"But I've never heard of 'class overloading'. What is the correct way to solve this problem, do you think?"
For this interface, you can use a template and specialization class (overloads):
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
}
You can also have a more flexible option by using a base class to provide an interface and the type selector inherits:
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 {
};
As for the last proposal, you can even extend it to a policy based template .
source to share