给定一个模板类,例如
template <class Key, class Value>
class CustomMap {
// standard map implementation here, with (say) 'put', 'contains' and 'get'
};
并假设我不关心 Value
参数(因为我希望将 map 作为一个集合使用),并且我不能使用标准 C++ 容器,建议的指示方式是什么?
一个选项是使用 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
对其进行补充。
注意:这些要求来自教育环境;因此,正在寻求最易读和最容易理解的答案。这个答案很可能是“添加一条评论来解释你为什么使用 int”...
最佳答案
您可以为 int
使用一个空类而不是一个容易混淆的别名:
struct nothing {};
CustomMap<std::string, nothing> map;
map.put("test", nothing());
我也不会使用 SHOUTY_CAPS;除了更难阅读之外,它们通常保留用于宏,以减少预处理器踩踏语言级名称的危险。
关于c++ - C++ 中 "unused template parameter"的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23544661/