0

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?

4

1 回答 1

1

只有类型由模板参数指定。构造函数 (1) 需要提供指定用于哈希表的类型的实例。实例本身可以是具有自己的数据成员并且使用非平凡构造创建的类。

该类的实现者选择不提供默认构造函数。这允许用户实现不可默认构造的哈希和相等比较操作,也就是说,类可以具有非平凡状态,其中没有默认构造函数可以使用的良好默认值。

您已经注意到构造函数 (2) 使用 ExtractKey 的默认构造,但仍允许哈希和相等比较器是非默认可构造的。

于 2013-06-22T02:41:21.930 回答