C ++中“未使用的模板参数”的最佳实践

时间:2014-05-08 14:25:38

标签: c++ templates void

给定模板类,例如

template <class Key, class Value> 
class CustomMap {
    // standard map implementation here, with (say) 'put', 'contains' and 'get'
};

并假设我不关心Value参数(因为我希望将地图用作集合),并且我不能使用标准C ++容器,建议的方法是什么?< / p>

一个选项是使用typedef:

typedef UNUSED int;
const UNUSED UNUSED_VALUE = 0;
CustomMap<std::string, UNUSED> map;
map.put("test", UNUSED_VALUE);
cout << map.contains("test");

在这种情况下你会推荐什么?显然,CustomMap<std::string, void>无法编译,因为对void的引用无效。我无法更改CustomMap的实现,也无法添加CustomSet来补充它。

注意:这些要求来自教育环境;因此,正在寻求最易读和可理解的答案。这个答案可能是&#34;添加注释,解释为什么你使用int&#34; ...

2 个答案:

答案 0 :(得分:7)

您可以使用空类而不是int的轻微混淆别名:

struct nothing {};
CustomMap<std::string, nothing> map;
map.put("test", nothing());

我也不会使用SHOUTY_CAPS;它们通常被保留用于宏,以减少预处理器踩踏语言级别名称的危险。

答案 1 :(得分:0)

就个人而言,如果他们必须是同一个名字,我可能会使用专业化:

template <typename T, typename... J>
class OptionalSet;

template <typename T>
class OptionalSet
{
  //implementation of non-keyed thing
};

template <typename T, typename J>
class OpionalSet
{
  //implimentation of keyed thing
};

但最重要的是一套和一张地图不一样,让他们成为同一个班级就是在寻找麻烦。

相关问题