samedi 28 janvier 2017

Differentiate multiple typedef on same type [duplicate]

This question already has an answer here:

I have two std::unordered_map<std::string, bool> that contain strings associated to two different objects:

std::unordered_map<std::string, bool> dogsMap;
std::unordered_map<std::string, bool> catsMap;

Since the way to declare those maps is really ugly I define two new types:

typedef std::unordered_map<std::string, bool> DogMap;
typedef std::unordered_map<std::string, bool> CatMap;  

I could define a single typedef std::unordered_map<std::string, bool> AnimalMap; and declare two AnimalMap, one for dogs and one for cats. What I want to achieve is that if I pass them as parameter in addAnimal(DogMap, CatsMap) I cannot swap them, otherwise raise a compiler error.

DogsMap d;
CatsMap c;

addAnimal(d, c); // ok
addAnimal(c, d); // want compiler error on type

void addAnimal(DogsMap, CatsMap)
{
    // do something...
    // don't need to compare key/value between them
}

Aucun commentaire:

Enregistrer un commentaire