Question

In SGI STL implementation <stl_hashtable.h> the hashtable class has a ctor like:

template <class Value, class Key, class HashFcn,
          class ExtractKey, class EqualKey,
          class Alloc>
class hashtable {
public:
  typedef Key key_type;
  typedef Value value_type;
  typedef HashFcn hasher;
  typedef EqualKey key_equal;
  //other type definitions

  hasher hash_funct() const { return hash; }
  key_equal key_eq() const { return equals; }

private:
  hasher hash;//hash function which might be a functor
  key_equal equals;//compare functor that returns two key is equal or not
  ExtractKey get_key;//functor used when we extract a key from value, see bkt_num


public:
    //There is no default ctor
  hashtable(size_type n, //------------(1)
            const HashFcn&    hf,
            const EqualKey&   eql,
            const ExtractKey& ext)
    : hash(hf), equals(eql), get_key(ext), num_elements(0)
  {
    initialize_buckets(n);
  }
  hashtable(size_type n, //------------(2)
        const HashFcn&    hf,
        const EqualKey&   eql)
: hash(hf), equals(eql), get_key(ExtractKey()), num_elements(0)
  {
    initialize_buckets(n);
  }
//...
}

I was wandering that since we have already declared the ExtractKey, HashFcn and the EqualKey as the template parameter, why they need a ctor defined in (1)? Isn't the parameter all unnecessary except size_type n? We can use HashFcn() ExtractKey() and so on. Like it did in (2) but not all of the three.

So is there any other further consideration of doing this?

Was it helpful?

Solution

Only the type is specified by the template parameter. The constructor (1) is needed to provide instances of the types specified for use in the hashtable. The instances themselves can be classes that have their own data members and have been created with a non-trivial construction.

The implementer of the class chose not to provide a default constructor. This allows a user to implement hash and equality comparison operations that are not default constructable, that is, the classes can have non-trivial state for which there isn't a good default value that would be used by the default constructor.

You've noted that constructor (2) uses a default construction of ExtractKey, but still allows the hash and equality comparator to be non-default constructable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top