跳过一个C ++模板参数

跳过一个C ++模板参数

问题描述:

C ++ hash_map具有以下模板参数:

A C++ hash_map has the following template parameters:

template<typename Key, typename T, typename HashCompare, typename Allocator>

如何在不指定HashCompare的情况下指定Allocator?

How can I specify a Allocator without specifying the HashCompare?

这不会编译:(

hash_map<EntityId, Entity*, , tbb::scalable_allocator>


您可以使用一个技巧,必须找出默认值,但它需要你知道类型的名称,因为它在 hash_map 中定义。

There's one trick you can use which will at least save you having to work out what the default is, but it does require that you know the name of the type as it is defined in hash_map.

hash_map可能被声明为:

The hash_map will probably be declared something like:

class allocator {};
class hash_compare {};

template<typename Key
  , typename T
  , typename HashCompare = hash_compare
  , typename Allocator = allocator>
class hash_map
{
public:
  typedef HashCompare key_compare;
  // ...
};

我们不能忽略hash的默认值,但我们可以使用成员typedef来引用默认值:

We cannot leave out the default for the hash, but we can refer to the default using the member typedef:

hash_map<EntityId
  , Entity*
  , hash_map<EntityId,Entity*>::key_compare  // find out the default hasher
  , tbb::scalable_allocator> hm;

如果你打算使用类型,那么创建一个typedef:

If you're going to use the type a lot, then create a typedef:

typedef hash_map<EntityId,Entity*>::key_compare EntityKeyCompare;

hash_map<EntityId
  , Entity*
  , EntityKeyCompare
  , tbb::scalable_allocator> hm;