mercredi 30 janvier 2019

strong type checking for user-defined types

sometimes we using using Key = uint32_t; to define the new type. The problem is - it is just alias. If you define two various types, they are not really type-checked:

using RowKey = uint32_t;
using ColKey = uint32_t;
std::map

<RowKey, std::map<ColKey, int>> myStorage;

RowKey keyR = 1;
ColKey keyC = 2;

int res1 = myStorage[keyR][keyC]; // it's ok
int res2 = myStorage[keyC][keyR]; // it's ok too, but it shouldn't compile!

A possible solution is to define a wrapper class around the int (or something else we have as key), but i think, this is overhead..

Is there any another solutions (maybe, in the new C++ standards)?

Aucun commentaire:

Enregistrer un commentaire