Вопрос

Given a template class such as

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

and assuming that I do not care for the Value parameter (as I wish to use the map as a set), and that I cannot use standard C++ containers, what is the recommended way to indicate this?

One option would be use a typedefs:

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

What would you recommend in this case? Evidently, CustomMap<std::string, void> does not compile, since references to void are invalid. I cannot change the implementation of CustomMap, nor can I add a CustomSet to complement it.

NOTE: these requirements come from an educational setting; therefore, the most readable and understandable answer is being sought. This answer may well be "add a comment explaining why you use an int"...

Это было полезно?

Решение

You could use an empty class rather than a mildly confusing alias for int:

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

I also wouldn't use SHOUTY_CAPS; as well as being harder to read, they're conventionally reserved for macros, to reduce the danger of the preprocessor stomping over language-level names.

Другие советы

Personally, if they HAD to be the same name, I'd probably use a specialization:

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

But the big thing is a set and a map are not the same, and making them the same class is asking for trouble.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top