Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skipping a C++ template parameter

Tags:

c++

templates

A C++ hash_map has the following template parameters:

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

How can I specify a Allocator without specifying the HashCompare?

This won't compile :(

hash_map<EntityId, Entity*, , tbb::scalable_allocator>
like image 314
jameszhao00 Avatar asked Aug 14 '09 04:08

jameszhao00


2 Answers

The simple answer is that you can't. You cannot skip a template parameter and have it choose the default value for the template. Your only option is to find out what the default is and insert it into your declaration.

like image 148
JaredPar Avatar answered Oct 26 '22 23:10

JaredPar


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.

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;
  // ...
};

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;

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;
like image 29
Richard Corden Avatar answered Oct 26 '22 23:10

Richard Corden