tuc*_*uxi 1 c++ templates void
给定一个模板类,如
template <class Key, class Value>
class CustomMap {
// standard map implementation here, with (say) 'put', 'contains' and 'get'
};
Run Code Online (Sandbox Code Playgroud)
并假设我不关心Value参数(因为我希望将地图用作一个集合),并且我不能使用标准C++容器,建议的方法是什么?
一种选择是使用typedef:
typedef UNUSED int;
const UNUSED UNUSED_VALUE = 0;
CustomMap<std::string, UNUSED> map;
map.put("test", UNUSED_VALUE);
cout << map.contains("test");
Run Code Online (Sandbox Code Playgroud)
在这种情况下你会推荐什么?显然,CustomMap<std::string, void>不编译,因为引用void无效.我不能改变执行CustomMap,也不能添加一个CustomSet补充它.
注意:这些要求来自教育环境; 因此,正在寻求最易读和可理解的答案.这个答案可能是"添加注释解释你为什么使用int"...
您可以使用空类而不是轻微混淆别名int:
struct nothing {};
CustomMap<std::string, nothing> map;
map.put("test", nothing());
Run Code Online (Sandbox Code Playgroud)
我也不会使用SHOUTY_CAPS; 除了难以阅读之外,它们通常被保留用于宏,以减少预处理器踩踏语言级名称的危险.
| 归档时间: |
|
| 查看次数: |
1277 次 |
| 最近记录: |