mardi 22 octobre 2019

Set a default constructor for an element in an unordered_map in case of [] operator

I have this class:

class test_t {

public:

  int value;

  test_t() { }

  test_t(int _value) : value(_value) { }

};

Now I have create a unordered_map with the a int value as key

std::unordered_map<int, test_t> map;

When I will use the operator [] if the key it not exist a new element will be add to the map calling the construct.

test_t & test = map[0];

Now it si possible to tell to the unordered_map to call the other constructor? i.e. is is possibile to do something like this?

std::unordered_map<int, test_t(5)> map;

in the means that every new element will be create whit the construction with value 5?

I know that i can create a construction like this:

test_t(int _value = 5) { }

however the class test is only a example of something more complex.

Aucun commentaire:

Enregistrer un commentaire