Reputation: 1139
Suppose that my hash table has words of different sizes and I want to keep track of words of different sizes in separate hash tables. Instead of creating 20 different hash table files for 20 different words sizes, is there a way to supply a const through a class?
Dynamic allocation is not an option, because it would cost 8 additional bytes for the pointer variable for each table entry.
template <//Is there a way to supply a const here to change the value of size?>
class HashTable
{
static const int size = #;
struct TableEntry
{
char words[size];
}
}
Upvotes: 0
Views: 55
Reputation: 106096
Integral template arguments are allowed:
template <int Size>
class HashTable ...
(I'd usually prefer size_t Size
, but you need to have included a header that defines it, such as <cstddef>
).
Separately, Captain Obvlious has a good point that most people considering such optimisations haven't actually got a need for them, and are just caught up in a conceptual concern. If you do have a proven need, regarding...
Dynamic allocation is not an option, because it would cost 8 additional bytes for the pointer variable for each table entry.
...there are other options, particularly easily implemented if you don't need to erase elements. For example, you could store the text in a contiguous memory region as in...
this\0that\0whatever\0huh\0
...then store offsets into that region in a single hash table. If you knew the input data wouldn't exceed 64k, you'd only need 2 bytes per offset. 4 bytes would allow up to 4GB of string data. And for longer words, you're then wasting less space for unused/empty hash table buckets so it counter-balances having the text stored elsewhere.
Upvotes: 2