【问题标题】:Skipping a C++ template parameter跳过 C++ 模板参数
【发布时间】:2009-08-14 18:01:37
【问题描述】:

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

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

如何在不指定 HashCompare 的情况下指定分配器?

这不会编译:(

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

【问题讨论】:

  • C++ 没有定义 hash_map 类型,更喜欢使用 C++ TR1 unordered_map

标签: c++ templates


【解决方案1】:

简单的答案是你不能。您不能跳过模板参数并让它选择模板的默认值。您唯一的选择是找出默认值并将其插入您的声明中。

【讨论】:

  • 虽然简单的方法行不通,但仍有其他方法可以实现。请参阅理查德和我的回答。
【解决方案2】:

您可以使用一种技巧,它至少可以让您不必计算默认值是什么,但它确实要求您知道在hash_map 中定义的类型的名称。

hash_map 可能会被声明为:

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

我们不能省略散列的默认值,但我们可以使用成员 typedef 引用默认值:

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

如果你要经常使用该类型,那么创建一个 typedef:

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

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

【讨论】:

    【解决方案3】:

    如果 has 映射类型有一些公共的 typedef 用于 HashCompare 模板参数,您可以编写一个使用普通哈希映射类型的元函数来获取标准比较器。像这样的:

    template< typename Key, typename T, typename Allocator>
    struct hash_map_type {
      typedef typename hash_map<Key,T>::key_compare key_compare;
      typedef mash_map<Key,T,key_compare,Allocator> result_t;
    };
    
    typedef hash_map_type<int,string,my_allocator>::result_type my_hash_map;
    

    然而,这取决于上面hash_map&lt;Key,T&gt;::key_compare 的可访问性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-07
      • 1970-01-01
      相关资源
      最近更新 更多